markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Simulating Thousands of Possible Allocations | stocks.head()
stock_normed = stocks/stocks.iloc[0]
stock_normed.plot()
stock_daily_ret = stocks.pct_change(1)
stock_daily_ret.head() | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Log Returns vs Arithmetic Returns
We will now switch over to using log returns instead of arithmetic returns, for many of our use cases they are almost the same,but most technical analyses require detrending/normalizing the time series and using log returns is a nice way to do that.
Log returns are convenient to work w... | log_ret = np.log(stocks / stocks.shift(1))
log_ret.head()
log_ret.hist(bins = 100,
figsize = (12, 6));
plt.tight_layout()
log_ret.describe().transpose()
log_ret.mean() * 252
# Compute pairwise covariance of columns
log_ret.cov()
log_ret.cov() * 252 # multiply by days | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Single Run for Some Random Allocation | # Set seed (optional)
np.random.seed(101)
# Stock Columns
print('Stocks')
print(stocks.columns)
print('\n')
# Create Random Weights
print('Creating Random Weights')
weights = np.array(np.random.random(4))
print(weights)
print('\n')
# Rebalance Weights
print('Rebalance to sum to 1.0')
weights = weights / np.sum(weigh... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Great! Now we can just run this many times over! | num_ports = 15000
all_weights = np.zeros((num_ports, len(stocks.columns)))
ret_arr = np.zeros(num_ports)
vol_arr = np.zeros(num_ports)
sharpe_arr = np.zeros(num_ports)
for ind in range(num_ports):
# Create Random Weights
weights = np.array(np.random.random(4))
# Rebalance Weights
weights = weights /... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Plotting the data | plt.figure(figsize = (12, 8))
plt.scatter(vol_arr,
ret_arr,
c = sharpe_arr,
cmap = 'plasma')
plt.colorbar(label = 'Sharpe Ratio')
plt.xlabel('Volatility')
plt.ylabel('Return')
# Add red dot for max SR
plt.scatter(max_sr_vol,
max_sr_ret,
c = 'red',
... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Mathematical Optimization
There are much better ways to find good allocation weights than just guess and check! We can use optimization functions to find the ideal weights mathematically!
Functionalize Return and SR operations | def get_ret_vol_sr(weights):
"""
Takes in weights, returns array or return,volatility, sharpe ratio
"""
weights = np.array(weights)
ret = np.sum(log_ret.mean() * weights) * 252
vol = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov() * 252, weights)))
sr = ret/vol
return np.array([ret, vol, ... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
To fully understand all the parameters, check out:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html | help(minimize) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
Optimization works as a minimization function, since we actually want to maximize the Sharpe Ratio, we will need to turn it negative so we can minimize the negative sharpe (same as maximizing the postive sharpe) | def neg_sharpe(weights):
return get_ret_vol_sr(weights)[2] * -1
# Contraints
def check_sum(weights):
'''
Returns 0 if sum of weights is 1.0
'''
return np.sum(weights) - 1
# By convention of minimize function it should be a function that returns zero for conditions
cons = ({'type' : 'eq', 'fun': c... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
All Optimal Portfolios (Efficient Frontier)
The efficient frontier is the set of optimal portfolios that offers the highest expected return for a defined level of risk or the lowest risk for a given level of expected return. Portfolios that lie below the efficient frontier are sub-optimal, because they do not provide e... | # Our returns go from 0 to somewhere along 0.3
# Create a linspace number of points to calculate x on
frontier_y = np.linspace(0, 0.3, 100) # Change 100 to a lower number for slower computers!
def minimize_volatility(weights):
return get_ret_vol_sr(weights)[1]
frontier_volatility = []
for possible_return in fr... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/09-Python-Finance-Fundamentals/02-Portfolio-Optimization.ipynb | arcyfelix/Courses | apache-2.0 |
2. Read in the hanford.csv file | df = pd.read_csv("hanford.csv")
df.head() | class6/donow/honjingyi_donow_6.ipynb | ledeprogram/algorithms | gpl-3.0 |
5. Create a linear regression model based on the available data to predict the mortality rate given a level of exposure | lm = smf.ols(formula="Mortality~Exposure",data=df).fit()
lm.params
intercept, slope = lm.params | class6/donow/honjingyi_donow_6.ipynb | ledeprogram/algorithms | gpl-3.0 |
6. Plot the linear regression line on the scatter plot of values. Calculate the r^2 (coefficient of determination) | df.plot(kind="scatter",x="Exposure",y="Mortality")
plt.plot(df["Exposure"],slope*df["Exposure"]+intercept,"-",color="red") | class6/donow/honjingyi_donow_6.ipynb | ledeprogram/algorithms | gpl-3.0 |
7. Predict the mortality rate (Cancer per 100,000 man years) given an index of exposure = 10 | mortality_rate = slope * 10 + intercept
mortality_rate | class6/donow/honjingyi_donow_6.ipynb | ledeprogram/algorithms | gpl-3.0 |
First I'm going to define a function which gets us an attendee's spending at random.
Don't worry about the implementation, just check the printed sample of 100 values generated
and see if it seems realistic. I think it is, but we can argue about this, sure.
You can adjust the algorithm and see the numbers with what you... | def get_spending_of_attendee():
if random.random() < 0.03: # Let's say 3% doesn't even care about the secret shop
return 0
return int((random.paretovariate(2) - 0.5) * 100)
print([get_spending_of_attendee() for _ in range(100)]) | viability.ipynb | Arcana/emoticharms.trade | gpl-2.0 |
Packs are identified by an ID of 0 to 5, and this function just hands out
an attendee's packs based on their spending. | def get_packs(spending):
return [random.randint(0, 5) for _ in range(math.floor(spending / 50))] | viability.ipynb | Arcana/emoticharms.trade | gpl-2.0 |
So here's the meat of the notebook. We get a random spending, the packs for that,
and try to redeem the stickers for the digital unlock. If we can't do that because
of dupes, we increment our userbase by one. If someone is not constrained by dupes,
they have no use for our site. This includes:
People who have less tha... | for _ in range(ATTENDEES):
spending = get_spending_of_attendee()
packs = get_packs(spending)
try:
while len(packs) > 5:
for pack_id in range(6):
packs.remove(pack_id)
except ValueError:
eligible_users.append(packs)
print(len(eligible_users)) | viability.ipynb | Arcana/emoticharms.trade | gpl-2.0 |
So, yeah. We have around 1,280 people who could even use the site. But:
We can't let all of them know that the site exists.
Since there's lots of people coming from abroad, most won't even have convenient Internet access.
Not all of them are going to bother (some of them already have one unlock redeemed).
If they are ... | pack_count = sum(len(get_packs(get_spending_of_attendee())) for _ in range(ATTENDEES))
print(pack_count) | viability.ipynb | Arcana/emoticharms.trade | gpl-2.0 |
Lets see what dataset we have loaded | df.education.unique()
#school, college, bachelor, master
df['education'] = df['education'].replace(['High School or Below'], 'school')
df['education'] = df['education'].replace(['Bechalor'], 'bachelor')
df['education'] = df['education'].replace(['Master or Above'], 'master')
df.to_csv('datasets/dataset.csv')
df[:10] | cleaning_up_dataset.ipynb | skcript/normalization | gpl-3.0 |
We don't need all the columns. Right? Let's drop the unneccessary things. | df = df.drop(['loan_id', 'effective_date', 'due_date', 'paid_off_time', 'past_due_days'], axis = 1)
# The dataframe holds the needed columns now. Cool.
df[:10] | cleaning_up_dataset.ipynb | skcript/normalization | gpl-3.0 |
In order to get the information of the whole dataframe, use info() | df.info()
# Lets clean the data and create columns if needed.
df['Gender'].unique() | cleaning_up_dataset.ipynb | skcript/normalization | gpl-3.0 |
We can see that our dateset has two unique string values for GENDER.
We can't assign numeric values like female = 1 and male = 2 because of feminism.
Just kidding. We shouldn't assign because then they will be a factor that denotes intensity. We want to differentiate our category.
So we are going to have sepeate colum... | df_sex = pd.get_dummies(df['Gender'])
df_sex[:10]
df = pd.concat([df,df_sex] , axis=1)
df[:10]
# Now drop the gender column from the main df and add df_sex to df
df = df.drop(['Gender'], axis=1)
df[:10]
# Similary lets do the same process for both load_status and education.
# This process is called Categorical C... | cleaning_up_dataset.ipynb | skcript/normalization | gpl-3.0 |
In machine learning, its always easier to compute if the values are between 1 to 0 (either positive or negative)
The process of converting them into such values is called normalization
There are many ways to normalize them.
Here I choose MinMaxScalar which converts the highest value to 1 and smallest value to 0. Remain... | df_to_norm = df[['Principal', 'terms', 'age']]
df_to_norm[:10]
df_norm = (df_to_norm - df_to_norm.min()) / (df_to_norm.max() - df_to_norm.min())
df_norm[:10]
df = df.drop(['Principal', 'terms', 'age'], axis=1)
df = pd.concat([df,df_norm], axis=1)
df[:10] | cleaning_up_dataset.ipynb | skcript/normalization | gpl-3.0 |
Customer Churn Analysis
Churn rate, when applied to a customer base, refers to the proportion of contractual customers or subscribers who leave a supplier during a given time period. It is a possible indicator of customer dissatisfaction, cheaper and/or better offers from the competition, more successful sales and/or m... | %%capture
import numpy as np
import pandas as pd
import h2o
from h2o.automl import H2OAutoML
from __future__ import print_function
import pandas_profiling
# Suppress unwatned warnings
import warnings
warnings.filterwarnings('ignore')
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
# Load our f... | model_management/Customer Churn with AutoML-Copy1.ipynb | Brett777/Predict-Churn | mit |
Load The Dataset | # Load some data
churnDF = pd.read_csv('https://trifactapro.s3.amazonaws.com/churn.csv', delimiter=',')
churnDF.head(5)
#%%capture
#pandas_profiling.ProfileReport(churnDF) | model_management/Customer Churn with AutoML-Copy1.ipynb | Brett777/Predict-Churn | mit |
Scatterplot Matrix |
# separate the calls data for plotting
churnDFs = churnDF.sample(frac=0.07) # Sample for speedy viz
churnDFs = churnDFs.replace([True,False],["Churn","Retain"])
churnDFs = churnDFs[['Account Length','Day Calls','Eve Calls','CustServ Calls','Churn']]
# Create scatter plot matrix of call data
splom = ff.create_scatterp... | model_management/Customer Churn with AutoML-Copy1.ipynb | Brett777/Predict-Churn | mit |
We can extract the coordinates of neighbour cells and try to fit a model without covariates | %time coords = map(lambda c : (c.centroid.x,c.centroid.y) , neighbour_cells)
lon,lat = zip(*coords)
X = pd.DataFrame([lon,lat])
Y = pd.DataFrame(y)
plt.figure(figsize=(17,11))
plt.scatter(lon,lat,c=Y)
data = pd.concat([Y,X.transpose()],axis=1)
data.columns = ['Presences','lon','lat']
# Import GPFlow
import GPflow ... | notebooks/Sandboxes/TensorFlow/.ipynb_checkpoints/Biospytial Models in GPFlow-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
len(X)
%time model.optimize() | model.kern.lengthscales = 320.49
model.kern.variance = 0.011
import numpy as np
Nn = 500
dsc = data
predicted_x = np.linspace(min(dsc.lon),max(dsc.lon),Nn)
predicted_y = np.linspace(min(dsc.lat),max(dsc.lat),Nn)
Xx, Yy = np.meshgrid(predicted_x,predicted_y)
## Fake richness
fake_sp_rich = np.ones(len(Xx.ravel()))
pred... | notebooks/Sandboxes/TensorFlow/.ipynb_checkpoints/Biospytial Models in GPFlow-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
Hello Networkx and Planarity
NetworkX Homepage
Planarity's Github Page
Pre-generated Graph DB - On Google Drive | # generate random graph
G = nx.generators.fast_gnp_random_graph(10, 0.4)
# check planarity and draw the graph
print("The graph is {0} planar".format("" if planarity.is_planar(G) else "not"))
if(planarity.is_planar(G)):
planarity.draw(G)
nx.draw(G) | old:misc/graph_analysis/check_planarity.ipynb | taesiri/noteobooks | mit |
Naïve Database creator script | # for the sake of this experiment, I'd used a fix 32x32 grid for adjacency matrix. This is a huge assumption, but this is just a stupid test!
def create_db():
# create empty list
planar_list = []
non_planar_list = []
# generate random graphs and store their adjacency lists
for p in range(1, 95... | old:misc/graph_analysis/check_planarity.ipynb | taesiri/noteobooks | mit |
Create a new database or load one! | planar_db = np.load("planar_db.npy")
non_planar_db = np.load("not_planar_db.npy")
np.random.shuffle(planar_db)
np.random.shuffle(non_planar_db)
all_data = np.append(planar_db, non_planar_db, axis=0)
all_labels = np.append(np.ones(len(planar_db)), np.zeros(len(non_planar_db))).astype(int)
# shuffling ...
permutation ... | old:misc/graph_analysis/check_planarity.ipynb | taesiri/noteobooks | mit |
Create a Simple ConvNet using PyTorch | import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPoo... | old:misc/graph_analysis/check_planarity.ipynb | taesiri/noteobooks | mit |
Let's plot some graphs that our ConvNet failed to classify correctly! | samples = np.random.choice(len(wrong_predictions), 3)
for i in samples:
G = nx.from_numpy_matrix(wrong_predictions[i])
isolated_edges = list(nx.isolates(G))
G.remove_nodes_from(isolated_edges)
plt.figure(figsize=(21, 5))
plt.subplot(1, 4, 1)
nx.draw(G, pos=nx.circular_layout (G) )
p... | old:misc/graph_analysis/check_planarity.ipynb | taesiri/noteobooks | mit |
Call the brownian function to simulate a Wiener process with 1000 steps and max time of 1.0. Save the results as two arrays t and W. | t,W = np.array(brownian(1,1000))
assert isinstance(t, np.ndarray)
assert isinstance(W, np.ndarray)
assert t.dtype==np.dtype(float)
assert W.dtype==np.dtype(float)
assert len(t)==len(W)==1000 | assignments/assignment03/NumpyEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Use np.diff to compute the changes at each step of the motion, dW, and then compute the mean and standard deviation of those differences. | #Standard numpy functions
dW = np.array(np.diff(W))
dW.mean()
dW.var(), dW.std()
assert len(dW)==len(W)-1
assert dW.dtype==np.dtype(float) | assignments/assignment03/NumpyEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Write a function that takes $W(t)$ and converts it to geometric Brownian motion using the equation:
$$
X(t) = X_0 e^{((\mu - \sigma^2/2)t + \sigma W(t))}
$$
Use Numpy ufuncs and no loops in your function. | def geo_brownian(t, W, X0, mu, sigma):
"Return X(t) for geometric brownian motion with drift mu, volatility sigma."""
#Plug into the equation above
X = X0 * np.exp((mu-sigma**2/2)**t + sigma * W)
return X
assert True # leave this for grading | assignments/assignment03/NumpyEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Use your function to simulate geometric brownian motion, $X(t)$ for $X_0=1.0$, $\mu=0.5$ and $\sigma=0.3$ with the Wiener process you computed above.
Visualize the process using plt.plot with t on the x-axis and X(t) on the y-axis. Label your x and y axes. | #Standard Plot
plt.plot(geo_brownian(t,W,1.0,0.5,0.3))
assert True # leave this for grading | assignments/assignment03/NumpyEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Read and tokenize moview review dataset | datafolder = '../data/scaledata/Dennis+Schwartz/'
rating_file = os.path.join(datafolder, 'rating.Dennis+Schwartz')
review_file = os.path.join(datafolder, 'subj.Dennis+Schwartz')
with open(rating_file, 'r') as f:
ratings = np.array([float(line.strip()) for line in f.readlines()])
with open(review_file, 'r') as f:
... | notebook/SupervisedTopicModel_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Infer topics with SupervisedLDA | n_topic = 50
r_var = 0.01
model = GibbsSupervisedLDA(n_doc, n_voca, n_topic, sigma=r_var)
model.fit(corpus, ratings)
for ti in model.eta.argsort():
top_words = get_top_words(model.TW, voca, ti, n_words=10)
print('Eta', model.eta[ti] ,'Topic', ti ,':\t', ','.join(top_words)) | notebook/SupervisedTopicModel_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Are we underfitting?
So far, our validation accuracy has generally been higher that our training accuracy
This leads to 2 questions:
1. How is this possible?
2. Is this desirable?
Answer 1):
Because of dropout. Dropout refers to a layer taht randomly deletes (i.e. sets to 0) each activation in the previous layer with p... | ??vgg_ft | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
py
def vgg_ft(out_dim):
vgg = Vgg16()
vgg.ft(out_fim)
model = vgg.model
return model | ??Vgg16.ft | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
py
def ft(self, num):
"""
Replace the last layer of the model with a Dense layer of num neurons.
Will also lock the weights of all layers except the new layer so that we only learn weights for the last layer in subsequent training.
Args:
num (int): Number of neurons in the Dense layer
Return... | model = vgg_ft(2) | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
...and load our fine-tuned weights from lesson 2. | model.load_weights(model_path + 'finetune3.h5') | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Now, let's train a few iterations w/o dropout. But first, let's pre-calculate the input to the fully connected layers - i.e. the Flatten() layer.
Because convolution layers take a lot of time to compute, but Dense layers do not. | model.summary()
layers = model.layers
# find the lasy convolution layer
last_conv_idx = [index for index, layer in enumerate(layers)
if type(layer) is Convolution2D][-1]
last_conv_idx
layers[last_conv_idx]
conv_layers = layers[:last_conv_idx+1]
conv_model = Sequential(conv_layers)
fc_layers = laye... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Now, we can use the exact same approach to create features as we used when we created the linear model from the imagenet predictions in lesson 2. | batches = get_batches(path+'train', shuffle=False, batch_size=batch_size)
val_batches = get_batches(path+'valid', shuffle=False, batch_size=batch_size)
val_classes = val_batches.classes
trn_classes = batches.classes
val_labels = onehot(val_classes)
trn_labels = onehot(trn_classes)
# Let's get the outputs of the conv ... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
For our new fully connected model, we'll create it using the exact same architecture as the last layers of VGG 16, so that we can conveniently copy pre-trained weights over from that model. | def proc_wgts(layer): return [o/2 for o in layer.get_weights()]
# Such a finely tuned model needs to be updated very slowly!!
opt = RMSprop(lr=0.00001, rho=0.7)
def get_fc_model():
model = Sequential([
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dense(4096, activ... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Reducing overfitting
Now we've gotten a model that overfits. So let's take a few steps to reduce this.
Approaches to reduce overfitting
Before relying on dropout or other regularization approches to reduce overfitting, try the following techniques first. Because regularization, by definition, biases our model towards s... | # dim_ordering='tf' uses tensorflow dimension ordering,
# which is the same order as matplotlib uses for display.
# Therefore when just using for display purposes, this is more convenient
gen = image.ImageDataGenerator(
rotation_range=10, width_shift_range=0.1,height_shift_range=0.1,
shear_range=0.15, zoom_ra... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
So to decide which augmentation methods to use, let's take a look at the generated imaged, and use our intuition. | # Create a 'batch' of a single image
img = np.expand_dims(ndimage.imread('data/dogscats/test/unknown/7.jpg'),0)
# Request the generator to create batches from this image
aug_iter = gen.flow(img)
# Get 8 examples of these augmentated images
aug_imgs = [next(aug_iter)[0].astype(np.uint8) for i in range(8)]
# The origin... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Now, it's time to add a small amount of data augmentation, and see if we can reduce overfitting. The approach will be identical to the method we used to finetune the dense layers in lesson2, except that will use a generator with augmentation configured. Here's how we set up the generator and create batches from it: | gen = image.ImageDataGenerator(rotation_range=15, width_shift_range=0.1,height_shift_range=0.1,
zoom_range=0.1,horizontal_flip=True)
batches = get_batches(path+'train', gen, batch_size=batch_size)
val_batches = get_batches(path+'valid', shuffle=False, batch_size=batch_size)
??get_batches | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
py
get_batches(dirname, gen=<keras.preprocessing.image.ImageDataGenerator object at 0x7fb1a30544e0>, shuffle=True, batch_size=4, class_mode='categorical', target_size=(224, 224))
When using data augmentation, we can't pre-compute our convolutional layer features, since randomized changes are being made to every i... | fc_model = get_fc_model()
for layer in conv_model.layers: layer.trainable = False
conv_model.add(fc_model) | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Now, we can compile, train, and save our model as usual - note we use fit_generator() since we want to pull random images from the directories on every batch | conv_model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
conv_model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=3,
validation_data=val_batches, nb_val_samples=val_batches.nb_sample)
conv_model.save_weights(model_path + 'aug1.h5')
conv_m... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Batch normalization
Batch normalization is a way to ensure that activations don't become too high or too low at any point in the model. Adjusting activiations so that are of similar scales is called normalization. It is very helpful for fast training - if some activations are very high, they will saturate the model and... | conv_layers[-1].output_shape[1:]
def get_bn_layers(p):
return [
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dense(4096, activation='relu'),
BatchNormalization(),
Dropout(p),
Dense(4096, activation='relu'),
BatchNormalization(),
... | deeplearning1/nbs/lesson3_yingchi.ipynb | yingchi/fastai-notes | apache-2.0 |
Compute source power using DICS beamformer
Compute a Dynamic Imaging of Coherent Sources (DICS)
:footcite:GrossEtAl2001 filter from
single-trial activity to estimate source power across a frequency band. This
example demonstrates how to source localize the event-related synchronization
(ERS) of beta band activity in th... | # Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
# Roman Goj <roman.goj@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import mne
from mne.datasets import somato
from... | 0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
We can now listen to the resulting audio with the beats marked by beeps. We can also visualize beat estimations. | import IPython
IPython.display.Audio(temp_dir.name + '/dubstep_beats.flac')
from pylab import plot, show, figure, imshow
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15, 6)
plot(audio)
for beat in beats:
plt.axvline(x=beat*44100, color='red')
plt.xlabel('Time (samples)')
pl... | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
BPM histogram
The BPM value output by RhythmExtactor2013 is the average of all BPM estimates done for each interval between two consecutive beats. Alternatively, we can analyze the distribution of all those intervals using BpmHistogramDescriptors. This is especially useful for music with a varying tempo (which is not t... | peak1_bpm, peak1_weight, peak1_spread, peak2_bpm, peak2_weight, peak2_spread, histogram = \
es.BpmHistogramDescriptors()(beats_intervals)
print("Overall BPM (estimated before): %0.1f" % bpm)
print("First histogram peak: %0.1f bpm" % peak1_bpm)
print("Second histogram peak: %0.1f bpm" % peak2_bpm)
fig, ax = plt.su... | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
BPM estimation with PercivalBpmEstimator
PercivalBpmEstimator is another algorithm for tempo estimation. | # Loading an audio file.
audio = es.MonoLoader(filename='../../../test/audio/recorded/dubstep.flac')()
# Compute BPM.
bpm = es.PercivalBpmEstimator()(audio)
print("BPM:", bpm) | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
BPM estimation for audio loops
The BPM detection algorithms we considered so far won't necessarily produce the best estimation on short audio inputs, such as audio loops used in music production. Still, it is possible to apply some post-processing heuristics under the assumption that the analyzed audio loop is expected... | # Our input audio is indeed a well-cut loop. Let's compute the BPM.
bpm = es.LoopBpmEstimator()(audio)
print("Loop BPM:", bpm) | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
BPM estimation with TempoCNN
Essentia supports inference with TensorFlow models for a variety of MIR tasks, in particular tempo estimation, for which we provide the TempoCNN models.
The TempoCNN algorithm outputs a global BPM estimation on the entire audio input as well as local estimations on short audio segments (pa... | !curl -SLO https://essentia.upf.edu/models/tempo/tempocnn/deeptemp-k16-3.pb
import essentia.standard as es
sr = 11025
audio_11khz = es.MonoLoader(filename='../../../test/audio/recorded/techno_loop.wav', sampleRate=sr)()
global_bpm, local_bpm, local_probs = es.TempoCNN(graphFilename='deeptemp-k16-3.pb')(audio_11khz)
... | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
We can plot a slice of the waveform on top of a grid with the estimated tempo to get visual verification | import numpy as np
duration = 5 # seconds
audio_slice = audio_11khz[:sr * duration]
plt.plot(audio_slice)
markers = np.arange(0, len(audio_slice), sr / (global_bpm / 60))
for marker in markers:
plt.axvline(x=marker, color='red')
plt.title("Audio waveform on top of a tempo grid")
show() | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
TempoCNN operates on audio slices of 12 seconds with an overlap of 6 seconds by default. Additionally, the algorithm outputs the local estimations along with their probabilities. The global value is computed by majority voting by default. However, this method is only recommended when a constant tempo can be assumed. | print('local BPM: {}'.format(local_bpm))
print('local probabilities: {}'.format(local_probs)) | src/examples/python/tutorial_rhythm_beatdetection.ipynb | MTG/essentia | agpl-3.0 |
line style or marker
character | description
-----------|-------------------------
'-' | solid line style
'--' | dashed line style
'-.' | dash-dot line style
':' | dotted line style
'.' | point marker
',' | pixel marker
'o' | circle marker
'v' | triangle_... | # Create a figure of size 8x6 inches, 80 dots per inch
plt.figure(figsize=(8, 6), dpi=80)
# Create a new subplot from a grid of 1x1
plt.subplot(1, 1, 1)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(X, C, color="bl... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Changing colors and line widths
Color Codes
character| color
----------|----------
'b' | blue
'g' | green
'r' | red
'c' | cyan
'm' | magenta
'y' | yellow
'k' | black
'w' | white | # Create a figure of size 8x6 inches, 80 dots per inch
plt.figure(figsize=(6, 4), dpi=20)
# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(X, C, color="red", linewidth=1.0, linestyle="-")
# Plot sine with a green continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, li... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Setting limits | plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(X, C, color="red", linewidth=1.0, linestyle="-")
# Plot sine with a green continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Setting ticks | plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])
# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(X, C, color="red", linewidth=1.0, linestyle="-")
# Plot sine with a green continuous line of width 1 (pixels)
plt.plot(X, S, color="blue", linewidth=1.0, linestyle="-") | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Setting tick labels
xticks and yticks accept two list as below -
[ticks values], [ticks name] | plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
# Plot cosine with a red continuous line of width 1 (pixels)
plt.plot(X, C, color="red", linewidth=1.0, linestyle="-")
# Plot sine with a blue continuous line o... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Moving spines | ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# Plot cosine with a blue continuo... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Adding a legend | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left') | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Annotate some points | t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fon... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
Devil is in the details | for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.an... | scikit-learn/MatPlotLib_01.ipynb | atulsingh0/MachineLearning | gpl-3.0 |
.. _tut_sensors_time_frequency:
Frequency and time-frequency sensors analysis
The objective is to show you how to explore the spectral content
of your data (frequency and time-frequency). Here we'll work on Epochs.
We will use the somatosensory dataset that contains so
called event related synchronizations (ERS) / desy... | import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet, psd_multitaper
from mne.datasets import somato | 0.12/_downloads/plot_sensors_time_frequency.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Inspect power
.. note::
The generated figures are interactive. In the topo you can click
on an image to visualize the data for one censor.
You can also select a portion in the time-frequency plane to
obtain a topomap for a certain time-frequency region. | power.plot_topo(baseline=(-0.5, 0), mode='logratio', title='Average power')
power.plot([82], baseline=(-0.5, 0), mode='logratio')
fig, axis = plt.subplots(1, 2, figsize=(7, 4))
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=8, fmax=12,
baseline=(-0.5, 0), mode='logratio', axes=axis[0],
... | 0.12/_downloads/plot_sensors_time_frequency.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The setup required to repeat these operations is explained in the introduction notebook. In case graphs do not appear in this page you can refer to the static version.
The next commands may be needed or not depending on your setup (i.e. if you use my docker setup): | import os
from pprint import pprint
import pandas
import sqlalchemy
# your postgres server IP
IP = 'localhost'
def sql(query, **kwargs):
"""helper function for SQL queries using the %(...) syntax
Parameters defined globally are replaced implicitely"""
params = globals().copy()
params.update(kwargs)
... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
Extraction of band data from the database
Now we can extract the information for the band I want. The SQL query will look for:
band name
artists linked to this band through the "member of" relationship
instrument/vocal role of this relationship
Let's start with some band you probably already know: | band_name = 'The Beatles' | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
The SQL query is a bit complicated because it uses a lot of different tables, I won't go into details. We store the result in a data structure called a PanDas DataFrame (df). | df = sql("""
SELECT b.name AS band,
m.name AS member,
m.gid AS mbid,
lat.name AS role,
to_date(to_char(l.begin_date_year, '9999') || '0101', 'YYYYMMDD') AS start,
to_date(to_char(l.end_date_year, '9999') || '0101', 'YYYYMMDD') AS end
FROM artist AS b
JOIN l_artist_artist ... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
The data is here, we just want to set a start date for Lennon's roles since it is not in the database. | import datetime
df['start'] = df['start'].fillna(datetime.date(1957, 1, 1))
df['mbid'] = df['mbid'].astype(str) # otherwise PanDas uses the UUID data type which will cause problems later.
df | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
Display a timeline with timesheet-advanced
The timesheet-advanced package requires the input data for the timeline to be inserted slightly differently from what we have in our dataframe df. Let us first copy our data in a new variable ts and simplify the dates to years. | ts = df.copy()
ts['start'] = ts['start'].apply(lambda date: date.year).astype(str)
ts['end'] = ts['end'].apply(lambda date: date.year).astype(str) | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
We need a 'label' field (we'll choose the band member name + instrument) and we need a 'type' which is a color. We choose colors to represent all possible roles (vocals, guitar, drums....) | ts['label'] = df['member'] + ' (' + df['role'] + ')'
ts
colors = dict(zip(sorted(set(ts['role'])), ['red', 'blue', 'yellow', 'green']))
print('Correspondance between colors and roles: {}'.format(colors))
ts['type'] = ts['role'].apply(lambda role: colors[role])
ts | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
We can also add a 'link' columns containing URLs to the MusicBrainz website: | ts['link'] = 'https://musicbrainz.org/artist/' + ts['mbid']
ts.drop('mbid', axis=1, inplace=True)
ts | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
The last preparation step is to transform this Python data structure into a Javascript one that the timesheet library can read. We're going to use the fact that a Python list and a Javascript array are very close (we could also use JSON format to transform our data into smething JavaScript-compatible). | bubbles = [ts.loc[i].to_dict() for i in range(len(ts))]
print('First bubble:')
pprint(bubbles[0]) | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
Perfect, bubbles contains our data. Time to do some javascript. The Jupyter notebook can display javascript code in an output cell by using the element.append magic.
To display the timeline inside this notebook we need to load the JS/CSS source of the timesheet-advanced package... | from IPython.display import HTML
HTML("""
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/ntucakovic/timesheet-advanced.js/ea3ee1ad/dist/timesheet.min.css" />
<script type="text/javascript" src="https://cdn.rawgit.com/ntucakovic/timesheet-advanced.js/ea3ee1ad/dist/timesheet-advanced.min.js"></script... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
... and to create an output container for our timeline. This cell be filled when the next cell code (new Timesheet(...)) will be executed. | %%javascript
// this must be executed before the "from IPython.display import Javascript" block
element.append('<div id="timesheet-container" style="width: 100%;height: 100%;"></div>'); | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
Last step: we call the Timesheet javascript command using the CSS/JS libraries loaded above, our input data (bubbles), the cell where we want our graph, and the timeline limit (min and max date). Executing the next cell will fill the output cell just above this block automatically. | from IPython.display import Javascript
Javascript("""
var bubbles = %s;
new Timesheet(bubbles, {
container: 'timesheet-container',
type: 'parallel',
timesheetYearMin: %s,
timesheetYearMax: %s,
theme: 'light'
});
""" % (bubbles, ts['start'].min(), ts['end'].max())) | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
We have our timeline now! As you can see, the same color is used for the same role consistently. The items on the timeline are clickable links bringing you to the artist page on MusicBrainz. If you can't see the timeline above you can find a static version on github.io
Display a timeline with vis.js
We can try to displ... | v = df.copy()
v['start'] = v['start'].apply(lambda date: date.isoformat())
v['end'] = v['end'].apply(lambda date: date.isoformat())
v.drop('mbid', axis=1, inplace=True)
v['type'] = v['role'].apply(lambda role: colors[role])
v['label'] = v['member'] + ' (' + v['role'] + ')'
v | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
This time we are not going to inject the data inside a javascript string executed by the notebook, we are going to attach the data as JSON to the webpage itself (window) so that vis.js can find it. | # Transform into JSON
data = [{'start': line.start,
'end': line.end,
'content': line.label,
'className': line.type
} for _, line in ts.iterrows()]
# Send to Javascript
import json
from IPython.display import Javascript
Javascript("""window.bandData={};""".format(json.dumps(data, inde... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
We need to load the default CSS (from cdnjs.cloudflare.com) and add our custom CSS on top: | %%html
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.1/vis-timeline-graph2d.min.css" />
%%html
<style type="text/css">
/* custom styles for individual items, load this after vis.css/vis-timeline-graph2d.min.css */
.vis-item.red {
background-color: red;
}... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
In order to load the JS library itself, we can use the require mechanism inside the notebook: | %%javascript
element.append('<div id="vis-container" style="width: 100%;height: 100%;"></div>');
requirejs.config({
paths: {
vis: '//cdnjs.cloudflare.com/ajax/libs/vis/4.20.1/vis'
}
});
require(['vis'], function(vis){
var data = new vis.DataSet(window.bandData);
var options = {
editable: false... | 1-timelines.ipynb | loujine/musicbrainz-dataviz | mit |
Keras 예제의 가중치 클러스터링
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/model_optimization/guide/clustering/clustering_example"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td>
<td><a target="_blank" href="https://colab.... | ! pip install -q tensorflow-model-optimization
import tensorflow as tf
from tensorflow import keras
import numpy as np
import tempfile
import zipfile
import os | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
클러스터링을 사용하지 않고 MNIST용 tf.keras 모델 훈련하기 | # Load MNIST dataset
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images = test_images / 255.0
# Define the model architecture.
model = keras.S... | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
기준 모델을 평가하고 나중에 사용할 수 있도록 저장하기 | _, baseline_model_accuracy = model.evaluate(
test_images, test_labels, verbose=0)
print('Baseline test accuracy:', baseline_model_accuracy)
_, keras_file = tempfile.mkstemp('.h5')
print('Saving model to: ', keras_file)
tf.keras.models.save_model(model, keras_file, include_optimizer=False) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
클러스터링을 사용하여 사전 훈련된 모델 미세 조정하기
사전 훈련된 전체 모델에 cluster_weights() API를 적용하여 압축 후 적절한 정확성을 유지하면서 모델 크기가 줄어드는 효과를 입증합니다. 해당 사용 사례에서 정확성과 압축률의 균형을 가장 잘 유지하는 방법은 포괄적 가이드의 레이어별 예를 참조하세요.
모델 정의 및 클러스터링 API 적용하기
모델을 클러스터링 API로 전달하기 전에 모델이 훈련되었고 수용 가능한 정확성을 보이는지 확인합니다. | import tensorflow_model_optimization as tfmot
cluster_weights = tfmot.clustering.keras.cluster_weights
CentroidInitialization = tfmot.clustering.keras.CentroidInitialization
clustering_params = {
'number_of_clusters': 16,
'cluster_centroids_init': CentroidInitialization.LINEAR
}
# Cluster a whole model
clustered... | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
모델을 미세 조정하고 기준 대비 정확성 평가하기
하나의 epoch 동안 클러스터링이 있는 모델을 미세 조정합니다. | # Fine-tune model
clustered_model.fit(
train_images,
train_labels,
batch_size=500,
epochs=1,
validation_split=0.1) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
이 예의 경우, 기준과 비교하여 클러스터링 후 테스트 정확성의 손실이 미미합니다. | _, clustered_model_accuracy = clustered_model.evaluate(
test_images, test_labels, verbose=0)
print('Baseline test accuracy:', baseline_model_accuracy)
print('Clustered test accuracy:', clustered_model_accuracy) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
클러스터링으로부터 6배 더 작은 모델 만들기
클러스터링의 압축 이점을 확인하려면 strip_clustering과 표준 압축 알고리즘(예: gzip 이용) 적용이 모두 필요합니다.
먼저, TensorFlow를 위한 압축 가능한 모델을 만듭니다. 여기서, strip_clustering은 훈련 중에만 클러스터링에 필요한 모든 변수(예: 클러스터 중심과 인덱스를 저장하기 위한 tf.Variable)를 제거합니다. 이러한 변수를 제거하지 않으면 추론 중에 모델 크기가 증가하게 됩니다. | final_model = tfmot.clustering.keras.strip_clustering(clustered_model)
_, clustered_keras_file = tempfile.mkstemp('.h5')
print('Saving clustered model to: ', clustered_keras_file)
tf.keras.models.save_model(final_model, clustered_keras_file,
include_optimizer=False) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
그런 다음, TFLite를 위한 압축 가능한 모델을 만듭니다. 클러스터링된 모델을 대상 백엔드에서 실행 가능한 형식으로 변환할 수 있습니다. TensorFlow Lite는 모바일 기기에 배포하는 데 사용할 수 있는 예입니다. | clustered_tflite_file = '/tmp/clustered_mnist.tflite'
converter = tf.lite.TFLiteConverter.from_keras_model(final_model)
tflite_clustered_model = converter.convert()
with open(clustered_tflite_file, 'wb') as f:
f.write(tflite_clustered_model)
print('Saved clustered TFLite model to:', clustered_tflite_file) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
실제로 gzip을 통해 모델을 압축하는 도우미 함수를 정의하고 압축된 크기를 측정합니다. | def get_gzipped_model_size(file):
# It returns the size of the gzipped model in bytes.
import os
import zipfile
_, zipped_file = tempfile.mkstemp('.zip')
with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:
f.write(file)
return os.path.getsize(zipped_file) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
클러스터링으로부터 모델이 6배 더 작아진 것을 확인하세요. | print("Size of gzipped baseline Keras model: %.2f bytes" % (get_gzipped_model_size(keras_file)))
print("Size of gzipped clustered Keras model: %.2f bytes" % (get_gzipped_model_size(clustered_keras_file)))
print("Size of gzipped clustered TFlite model: %.2f bytes" % (get_gzipped_model_size(clustered_tflite_file))) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
가중치 클러스터링과 훈련 후 양자화를 결합하여 8배 더 작은 TFLite 모델 만들기
추가적인 이점을 얻기 위해 클러스터링한 모델에 훈련 후 양자화를 적용할 수 있습니다. | converter = tf.lite.TFLiteConverter.from_keras_model(final_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()
_, quantized_and_clustered_tflite_file = tempfile.mkstemp('.tflite')
with open(quantized_and_clustered_tflite_file, 'wb') as f:
f.write(tflite_quant_model)
... | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF에서 TFLite로 정확성이 지속되는지 확인하기
테스트 데이터세트에서 TFLite 모델을 평가하는 도우미 함수를 정의합니다. | def eval_model(interpreter):
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
# Run predictions on every image in the "test" dataset.
prediction_digits = []
for i, test_image in enumerate(test_images):
if i % 1000 == 0:
print('Eva... | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
클러스터링되고 양자화된 모델을 평가한 다음, TensorFlow의 정확성이 TFLite 백엔드까지 유지되는지 확인합니다. | interpreter = tf.lite.Interpreter(model_content=tflite_quant_model)
interpreter.allocate_tensors()
test_accuracy = eval_model(interpreter)
print('Clustered and quantized TFLite test_accuracy:', test_accuracy)
print('Clustered TF test accuracy:', clustered_model_accuracy) | site/ko/model_optimization/guide/clustering/clustering_example.ipynb | tensorflow/docs-l10n | apache-2.0 |
8124 instances in my datafile is confirmed. <br>
Below is the list of features and their coding copied from the database description file.
1. cap-shape: bell=b,conical=c,convex=x,flat=f,knobbed=k,sunken=s <br>
2. cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s <br>
3. cap-color: brown=n,buff=b,cinnamon=c,gray=g,gree... | headers = ['classif','cap_shape','cap_surface','cap_colour','bruises','odor','gill_attach','gill_space','gill_size',
'gill_color','stalk_shape','stalk_root','stalk_surf_above_ring','stalk_surf_below_ring',
'stalk_color_above_ring','stalk_color_below_ring','veil_type','veil_color','ring_number',
... | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
As expected, all of the values across all features are categorical. Later, I have encode those into numerical values. | table = pd.crosstab(index=df['classif'], columns="count")
table
fig = plt.figure(figsize=(2,2))
ax1 = fig.add_subplot(111)
ax1.set_xlabel('classification')
ax1.set_ylabel('count')
ax1.set_title("By classification")
df['classif'].value_counts().plot(kind='bar',color = '#4C72B0') | examples/dulybina/1_exploratory_analysis.ipynb | georgetown-analytics/machine-learning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.