markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Now we create a new classifier and train it with this output and the labels from ground truth
Classifier is copied from our first VGG style network | input_shape = bottleneck_features_train.shape[1:]
from keras.models import Model
from keras.layers import Dense, Dropout, Flatten, Input
# try and vary between .4 and .75
drop_out = 0.50
inputs = Input(shape=input_shape)
x = Flatten()(inputs)
# this is an additional dropout to compensate for the missing one after ... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
This is a very simple architecture and should train pretty fast
it overfits by quite a bit | %time history = classifier_model.fit(bottleneck_features_train, y_train, epochs=500, batch_size=BATCH_SIZE, validation_split=0.2, callbacks=[tb_callback])
# more epochs might be needed for original data
# %time history = classifier_model.fit(bottleneck_features_train, y_train, epochs=2000, batch_size=BATCH_SIZE, valida... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
Issue 1: We have two separate models now
How do we evaluate?
How to save model for later prediction use / deployment? | from keras import models
combined_model = models.Sequential()
combined_model.add(vgg_model)
combined_model.add(classifier_model)
combined_model.summary()
combined_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
train_loss, train_accuracy = combined_... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
Issue 2: Whatever we do, we overfit, much more than 85% on test not possible
for non augmented data it might even be as low as 70%
first thing we could try: maybe bottlebeck feature being 2x2 is too small, we could compensate by scaling images up to 128x128 or even 256x256
this can indeed bring up test score to 90%
ho... | len(vgg_model.layers)
vgg_model.layers
first_conv_layer = vgg_model.layers[1]
first_conv_layer.trainable
# set the first 15 layers (up to the last conv block)
# to non-trainable (weights will not be updated)
# so, the general features are kept and we (hopefully) do not have overfitting
non_trainable_layers = vgg_mo... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
We then tweak the complete model by very slowly re-retraining classifier and final convolutional block
slow learning prevents us from ruining previous good results
leave everthing else in place
earlier layers hopefully already encode common feaure channels
less risk of overfitting
earlier layers are more general
model... | from keras import optimizers
# compile the model with a SGD/momentum optimizer
# and a very slow learning rate
# make updates very small and non adaptive so we do not ruin previous learnings
combined_model.compile(loss='categorical_crossentropy',
optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
90% for validation is quite a bit of improvement, might even increase when we train for a bit longer
Metrics for Augmented Data
Accuracy
Validation Accuracy | train_loss, train_accuracy = combined_model.evaluate(X_train, y_train, batch_size=BATCH_SIZE)
train_loss, train_accuracy
test_loss, test_accuracy = combined_model.evaluate(X_test, y_test, batch_size=BATCH_SIZE)
test_loss, test_accuracy
# complete original non augmented speed limit signs
original_loss, original_accura... | notebooks/workshops/tss/cnn-imagenet-retrain.ipynb | DJCordhose/ai | mit |
Activation Functions
Q1. Apply relu, elu, and softplus to x. | _x = np.linspace(-10., 10., 1000)
x = tf.convert_to_tensor(_x)
relu = tf.nn.relu(x)
elu = tf.nn.elu(x)
softplus = tf.nn.softplus(x)
with tf.Session() as sess:
_relu, _elu, _softplus = sess.run([relu, elu, softplus])
plt.plot(_x, _relu, label='relu')
plt.plot(_x, _elu, label='elu')
plt.plot(_x, _softpl... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q2. Apply sigmoid and tanh to x. | _x = np.linspace(-10., 10., 1000)
x = tf.convert_to_tensor(_x)
sigmoid = tf.nn.sigmoid(x)
tanh = tf.nn.tanh(x)
with tf.Session() as sess:
_sigmoid, _tanh = sess.run([sigmoid, tanh])
plt.plot(_x, _sigmoid, label='sigmoid')
plt.plot(_x, _tanh, label='tanh')
plt.legend(bbox_to_anchor=(0.5, 1.0))
plt.... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q3. Apply softmax to x. | _x = np.array([[1, 2, 4, 8], [2, 4, 6, 8]], dtype=np.float32)
x = tf.convert_to_tensor(_x)
out = tf.nn.softmax(x, dim=-1)
with tf.Session() as sess:
_out = sess.run(out)
print(_out)
assert np.allclose(np.sum(_out, axis=-1), 1) | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q4. Apply dropout with keep_prob=.5 to x. | _x = np.array([[1, 2, 4, 8], [2, 4, 6, 8]], dtype=np.float32)
print("_x =\n" , _x)
x = tf.convert_to_tensor(_x)
out = tf.nn.dropout(x, keep_prob=0.5)
with tf.Session() as sess:
_out = sess.run(out)
print("_out =\n", _out) | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Fully Connected
Q5. Apply a fully connected layer to x with 2 outputs and then an sigmoid function. | x = tf.random_normal([8, 10])
out = tf.contrib.layers.fully_connected(inputs=x, num_outputs=2,
activation_fn=tf.nn.sigmoid,
weights_initializer=tf.contrib.layers.xavier_initializer())
with tf.Session() as sess:
sess.run(tf.global_varia... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Convolution
Q6. Apply 2 kernels of width-height (2, 2), stride 1, and same padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(2, 3, 3, 3), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(2, 2, 3, 2), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
out = tf.nn.conv2d(x, filter, strides=[1, 1, 1, 1], padding="SAME")
init = tf.global_variables_... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q7. Apply 3 kernels of width-height (2, 2), stride 1, dilation_rate 2 and valid padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 10, 10, 3), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(2, 2, 3, 2), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
out = tf.nn.atrous_conv2d(x, filter, padding="VALID", rate=2)
init = tf.global_variables_init... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q8. Apply 4 kernels of width-height (3, 3), stride 2, and same padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 10, 10, 5), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(3, 3, 5, 4), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
out = tf.nn.conv2d(x, filter, strides=[1, 2, 2, 1], padding="SAME")
init = tf.global_variable... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q9. Apply 4 times of kernels of width-height (3, 3), stride 2, and same padding to x, depth-wise. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 10, 10, 5), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(3, 3, 5, 4), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
out = tf.nn.depthwise_conv2d(x, filter, strides=[1, 2, 2, 1], padding="SAME")
init = tf.globa... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q10. Apply 5 kernels of height 3, stride 2, and valid padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 10, 5), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(3, 5, 5), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
out = tf.nn.conv1d(x, filter, stride=2, padding="VALID")
init = tf.global_variables_initializer()
wi... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q11. Apply conv2d transpose with 5 kernels of width-height (3, 3), stride 2, and same padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 5, 5, 4), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(3, 3, 5, 4), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
shp = x.get_shape().as_list()
output_shape = [shp[0], shp[1]*2, shp[2]*2, 5]
out = tf.nn.conv2d... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q12. Apply conv2d transpose with 5 kernels of width-height (3, 3), stride 2, and valid padding to x. | tf.reset_default_graph()
x = tf.random_uniform(shape=(4, 5, 5, 4), dtype=tf.float32)
filter = tf.get_variable("filter", shape=(3, 3, 5, 4), dtype=tf.float32,
initializer=tf.random_uniform_initializer())
shp = x.get_shape().as_list()
output_shape = [shp[0], (shp[1]-1)*2+3, (shp[2]-1)*2+3, 5]
out = ... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q13. Apply max pooling and average pooling of window size 2, stride 1, and valid padding to x. | _x = np.zeros((1, 3, 3, 3), dtype=np.float32)
_x[0, :, :, 0] = np.arange(1, 10, dtype=np.float32).reshape(3, 3)
_x[0, :, :, 1] = np.arange(10, 19, dtype=np.float32).reshape(3, 3)
_x[0, :, :, 2] = np.arange(19, 28, dtype=np.float32).reshape(3, 3)
print("1st channel of x =\n", _x[:, :, :, 0])
print("\n2nd channel of x =\... | programming/Python/tensorflow/exercises/Neural_Network_Part1_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
For the classification task, we will build a ridge regression model, and train it on a part of the full dataset | from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=120, random_state = 1960)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df_orig[lFeatures].values,
df_orig['TGT'... | doc/sklearn_reason_codes_RandomForest.ipynb | antoinecarme/sklearn_explain | bsd-3-clause |
Model Explanation
The goal here is to be able, for a given individual, the impact of each predictor on the final score.
For our model, we will do this by analyzing cross statistics between (binned) predictors and the (binned) final score.
For each score bin, we fit a linear model locally and use it to explain the scor... | from sklearn.linear_model import *
def create_score_stats(df, feature_bins = 4 , score_bins=30):
df_binned = df.copy()
df_binned['Score'] = clf.predict_proba(df[lFeatures].values)[:,0]
df_binned['Score_bin'] = pd.qcut(df_binned['Score'] , q=score_bins, labels=False, duplicates='drop')
df_binned['Score_b... | doc/sklearn_reason_codes_RandomForest.ipynb | antoinecarme/sklearn_explain | bsd-3-clause |
For simplicity, to describe our method, we use 5 score bins and 5 predictor bins.
We fit our local models on the training dataset, each model is fit on the values inside its score bin. |
(df_cross_stats , per_bin_classifiers , per_bin_coefficients, per_bin_intercepts) = create_score_stats(df_train , feature_bins=5 , score_bins=10)
def debrief_score_bin_classifiers(bin_classifiers):
binned_features = [col + '_bin' for col in lFeatures]
score_classifiers_df = pd.DataFrame(index=(['intercept'] ... | doc/sklearn_reason_codes_RandomForest.ipynb | antoinecarme/sklearn_explain | bsd-3-clause |
From the table above, we see that lower score values (score_bin_0) are all around zero probability and are not impacted by the predictor values, higher score values (score_bin_5) are all around 1 and are also not impacted. This is what one expects from a good classification model.
in the score bin 3, the score values i... | for col in lFeatures:
lcoef = df_cross_stats['Score_bin'].apply(lambda x : per_bin_coefficients.get(x).get(col))
lintercept = df_cross_stats['Score_bin'].apply(lambda x : per_bin_intercepts.get(x))
lContrib = lcoef * df_cross_stats[col + '_bin'] + lintercept/len(lFeatures)
df1 = pd.DataFrame();
df1[... | doc/sklearn_reason_codes_RandomForest.ipynb | antoinecarme/sklearn_explain | bsd-3-clause |
The previous sample, shows that the first individual lost 0.000000 score points due to the feature $X_1$, gained 0.003994 with the feature $X_2$, etc
Reason Codes
The reason codes are a user-oriented representation of the decision making process. These are the predictors ranked by their effects. | import numpy as np
reason_codes = np.argsort(df_cross_stats[[col + '_Effect' for col in lFeatures]].values, axis=1)
df_rc = pd.DataFrame(reason_codes, columns=['reason_idx_' + str(NC-c) for c in range(NC)])
df_rc = df_rc[list(reversed(df_rc.columns))]
df_rc = pd.concat([df_cross_stats , df_rc] , axis=1)
for c in range(... | doc/sklearn_reason_codes_RandomForest.ipynb | antoinecarme/sklearn_explain | bsd-3-clause |
The markov chain seems to be irreducible
One way to obtain the stationary state is to look at the eigen vectors correspendoing to the eigen value of 1. However, the eigen vectors come out to be imaginary. This seemed to be an issue wwith the solver so I relied on solving the system of equation: $\pi = P\pi$ | w, v = LA.eig(P)
for i in range(0,6):
print 'Eigen value: {}\n Eigen vector: {}\n'.format(w[i],v[:,i])
## Solve for (I-Q)^{-1}
iq = np.linalg.inv(np.eye(5)-qq)
iq_phi = iq[0,0]
iq_alpha = iq[1,1]
iq_beta = iq[2,2]
iq_alphabeta = iq[3,3]
iq_pol = iq[4,4]
| 2015_Fall/MATH-578B/Homework1/Homework1.ipynb | saketkc/hatex | mit |
EDIT: I made correction to solve for corrected $\pi$, by acounting for $P^T$ and not $P$ | A = np.eye(6)-P.T
A[-1,:] = [1,1,1,1,1,1]
B = [0,0,0,0,0,1]
X=np.linalg.solve(A,B)
print(X)
| 2015_Fall/MATH-578B/Homework1/Homework1.ipynb | saketkc/hatex | mit |
Stationary state is given by $\pi = (0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)$ The mean number of visits per unit time to $\dagger$ are $\frac{1}{\pi_6} = 6$ However strangely this does not satisfy $\pi=P\pi$. I was not able to figure out where I went wrong.
EDIT: I made correction to solve for corrected $\pi$, ... | #EDIT: I made correction to solve for corrected $\pi$, by acounting for $P^T$ and not $P$
print('\pi*P={}\n'.format(X*P))
print('But \pi={}'.format(X)) | 2015_Fall/MATH-578B/Homework1/Homework1.ipynb | saketkc/hatex | mit |
Simulating the chain:
General strategy: Generate a random number $\longrightarrow$ Select a state $\longrightarrow$ Jump to state $\longrightarrow$ Repeat | ## phi
np.random.seed(1)
PP = {}
PP['phi']= [1-k_a-k_b, k_a ,k_b, 0, 0, 0]
PP['alpha'] = [k_a, 1-k_a-k_b, 0, k_b, 0, 0]
PP['beta'] = [k_b, 0, 1-k_a-k_b, k_a, 0, 0]
PP['ab']= [0, k_b, k_a, 1-k_a-k_b-k_p, k_p, 0]
PP['pol']= [0, 0, 0, 0, 0, 1]
PP['d']= [0, 0, 0, 1, 0, 0]
##For $h(\phi)$
x0='phi'
x='phi'
def h(x):
s... | 2015_Fall/MATH-578B/Homework1/Homework1.ipynb | saketkc/hatex | mit |
Part (a,b,c) | print(r'$h(\phi)$: From simulation: {}; From calculation: {}'.format(h('phi'),iq_phi))
print(r'$h(\alpha)$: From simulation: {}; From calculation: {}'.format(h('alpha'),iq_alpha))
print(r'$h(\beta)$: From simulation: {}; From calculation: {}'.format(h('beta'),iq_beta))
print(r'$h(\alpha+\beta)$: From simulation: ... | 2015_Fall/MATH-578B/Homework1/Homework1.ipynb | saketkc/hatex | mit |
1 - Gradient Descent
A simple optimization method in machine learning is gradient descent (GD). When you take gradient steps with respect to all $m$ examples on each step, it is also called Batch Gradient Descent.
Warm-up exercise: Implement the gradient descent update rule. The gradient descent rule is, for $l = 1, ... | # GRADED FUNCTION: update_parameters_with_gd
def update_parameters_with_gd(parameters, grads, learning_rate):
"""
Update parameters using one step of gradient descent
Arguments:
parameters -- python dictionary containing your parameters to be updated:
parameters['W' + str(l)] =... | deeplearning.ai/C2.ImproveDeepNN/week2/assignment/Optimization+methods.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
Expected Output:
<table>
<tr>
<td > **W1** </td>
<td > [[ 1.63535156 -0.62320365 -0.53718766]
[-1.07799357 0.85639907 -2.29470142]] </td>
</tr>
<tr>
<td > **b1** </td>
<td > [[ 1.74604067]
[-0.75184921]] </td>
</tr>
<tr>
<td > **W2** </td>
<t... | # GRADED FUNCTION: random_mini_batches
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (... | deeplearning.ai/C2.ImproveDeepNN/week2/assignment/Optimization+methods.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
Expected Output:
<table style="width:50%">
<tr>
<td > **shape of the 1st mini_batch_X** </td>
<td > (12288, 64) </td>
</tr>
<tr>
<td > **shape of the 2nd mini_batch_X** </td>
<td > (12288, 64) </td>
</tr>
<tr>
<td > **shape of the 3rd mini_batch_X** </td>
... | # GRADED FUNCTION: initialize_velocity
def initialize_velocity(parameters):
"""
Initializes the velocity as a python dictionary with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Argumen... | deeplearning.ai/C2.ImproveDeepNN/week2/assignment/Optimization+methods.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
Expected Output:
<table style="width:90%">
<tr>
<td > **W1** </td>
<td > [[ 1.62544598 -0.61290114 -0.52907334]
[-1.07347112 0.86450677 -2.30085497]] </td>
</tr>
<tr>
<td > **b1** </td>
<td > [[ 1.74493465]
[-0.76027113]] </td>
</tr>
<tr>
<td > **W2** </... | # GRADED FUNCTION: initialize_adam
def initialize_adam(parameters) :
"""
Initializes v and s as two python dictionaries with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Arguments:... | deeplearning.ai/C2.ImproveDeepNN/week2/assignment/Optimization+methods.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
Expected Output:
<table style="width:40%">
<tr>
<td > **v["dW1"]** </td>
<td > [[ 0. 0. 0.]
[ 0. 0. 0.]] </td>
</tr>
<tr>
<td > **v["db1"]** </td>
<td > [[ 0.]
[ 0.]] </td>
</tr>
<tr>
<td > **v["dW2"]** </td>
<td > [[ 0. 0. 0.]
[ 0. 0.... | # GRADED FUNCTION: update_parameters_with_adam
def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate = 0.01,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):
"""
Update parameters using Adam
Arguments:
parameters -- python dictionary containing your... | deeplearning.ai/C2.ImproveDeepNN/week2/assignment/Optimization+methods.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
see tut-section-subselect-epochs for details.
The tutorials tut-epochs-class and tut-evoked-class have many
more details about working with the ~mne.Epochs and ~mne.Evoked classes.
Amplitude and latency measures
It is common in ERP research to extract measures of amplitude or latency to
compare across different conditi... | # Define a function to print out the channel (ch) containing the
# peak latency (lat; in msec) and amplitude (amp, in µV), with the
# time range (tmin and tmax) that were searched.
# This function will be used throughout the remainder of the tutorial
def print_peak_measures(ch, tmin, tmax, lat, amp):
print(f'Channe... | 0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
3. Enter BigQuery Anonymize Query Recipe Parameters
Ensure you have user access to both datasets.
Provide the source project, dataset and query.
Provide the destination project, dataset, and table.
Modify the values below for your use case, can be done multiple times, then click play. | FIELDS = {
'auth_read':'service', # Credentials used.
'from_project':'', # Original project to read from.
'from_dataset':'', # Original dataset to read from.
'from_query':'', # Query to read data.
'to_project':None, # Anonymous data will be writen to.
'to_dataset':'', # Anonymous data will be writen t... | colabs/anonymize_query.ipynb | google/starthinker | apache-2.0 |
4. Execute BigQuery Anonymize Query
This does NOT need to be modified unless you are changing the recipe, click play. | from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields
TASKS = [
{
'anonymize':{
'auth':{'field':{'name':'auth_read','kind':'authentication','order':0,'default':'service','description':'Credentials used.'}},
'bigquery':{
'from':{
'proj... | colabs/anonymize_query.ipynb | google/starthinker | apache-2.0 |
Reading input-output data: | # reading stimulus
Stim = np.array(pd.read_csv(os.path.join(data_path,'Stim.csv'),header = None))
# reading location of spikes
tsp = np.hstack(np.array(pd.read_csv(os.path.join(data_path,'tsp.csv'),header = None))) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Extracting a spike train from spike positions: | dt = 0.01
tsp_int = np.ceil((tsp - dt*0.001)/dt)
tsp_int = np.reshape(tsp_int,(tsp_int.shape[0],1))
tsp_int = tsp_int.astype(int)
y = np.array([item in tsp_int for item in np.arange(Stim.shape[0]/dt)+1]).astype(int) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Displaying a subset of the spike train: | fig, ax = plt.subplots(figsize=(16, 2))
fig = ax.matshow(np.reshape(y[:1000],(1,len(y[:1000]))),cmap = 'Greys',aspect = 15) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Creating filters: | # create a stimulus filter
kpeaks = np.array([0,round(20/3)])
pars_k = {'neye':5,'n':5,'kpeaks':kpeaks,'b':3}
K,K_orth,kt_domain = filters.createStimulusBasis(pars_k, nkt = 20)
# create a post-spike filter
hpeaks = np.array([0.1,2])
pars_h = {'n':5,'hpeaks':hpeaks,'b':.4,'absref':0.}
H,H_orth,ht_domain = filters.crea... | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Conditional Intensity (spike rate):
$$\lambda_{\beta} = \exp(K(\beta_k)Stim + H(\beta_h)y + dc)$$
($\beta_k$ and $\beta_h$ are the unknown coefficients of the filters and $dc$ is the direct current).
Since the convolution is a linear operation the intensity can be written in the following form:
$$\lambda_{\beta} = \exp... | M_k = lk.construct_M_k(Stim,K,dt)
M_h = lk.construct_M_h(tsp,H_orth,dt,Stim) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Combining $M_k$, $M_h$ and $\textbf{1}$ into one covariate matrix: | M = np.hstack((M_k,M_h,np.ones((M_h.shape[0],1)))) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
The conditional intensity becomes:
$$ \lambda_{\beta} = \exp(M\beta) $$
($\beta$ contains all the unknown parameters).
Create a Poisson process model with this intensity: | model = PP.PPModel(M.T,dt = dt/100) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Setting initial parameters for optimization: | coeff_k0 = np.array([-0.02304,
0.12903,
0.35945,
0.39631,
0.27189,
0.22003,
-0.17457,
0.00482,
-0.09811,
0.04823])
coeff_h0 = np.zeros((5,))
dc0 = 0
pars0 = np.hstack((coeff_k0,coeff_h0,dc0))
# pars0 = np.hstack((np.zeros((10,)),np.ones((5,)),0)) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Fitting the likelihood (here using Limited Memory BFGS method with 500 iterations): | res = model.fit(y,start_coef = pars0,maxiter = 500,method = 'L-BFGS-B') | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Optimization results: | print(res) | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Creating the predicted filters: | k_coeff_predicted = res.x[:10]
h_coeff_predicted = res.x[10:15]
kfilter_predicted = np.dot(K,k_coeff_predicted)
hfilter_predicted = np.dot(H_orth,h_coeff_predicted)
k_coeff = np.array([ 0.061453,0.284916,0.860335,1.256983,0.910615,0.488660,-0.887091,0.097441,0.026607,-0.090147])
h_coeff = np.array([-15.18,38.24,-67.5... | notebooks/MLE_singleNeuron.ipynb | valentina-s/GLM_PythonModules | bsd-2-clause |
Configuring maps and loading data about where the complaints have occured. Observe, to sucesfully configure the Google Maps you have to create an API Key (You can generate one from this site: https://developers.google.com/maps/documentation/javascript/get-api-key) and change in the line 'plot.api_key = ""' | map_options = GMapOptions(lat=39.151042, lng=-77.193023, map_type="roadmap", zoom=11)
plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options)
plot.title.text = "Montgomery County"
# For GMaps to function, Google requires you obtain and enable an API key:
#
# https://developers.googl... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
Load data in using read_csv function, configure which tools will be available in the plot. | #Loading dataset from Montgomery County complaint dataset
monty_data = pd.read_csv("MontgomeryCountyCrime2013.csv")
latitude_data = monty_data["Latitude"]
longitude_data = monty_data["Longitude"]
monty_data.head()
| EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
Categorizing complaint classes | #Creating a master class to categorize crimes
classaux = monty_data["Class"]/100
classaux = classaux.astype(int)
classaux = classaux*100
#Inserting this new data in the dataset
monty_data["MasterClass"] = classaux
#print(montydata.groupby("Class")["Class Description"].mean())
#Sort by Class of complaint to analise mas... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
Ploting the geographic data in Google Maps. Note that the 'show' function receives another parameter 'notebook_handle=True' responsible for tell Bhoke to do a inline plot | show(plot,notebook_handle=True) | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>Which sort of complaints are most common, TOP 10?</h3> | #Using the agg function allows you to calculate the frequency for each group using the standard library function len.
#Sorting the result by the aggregated column code_count values, in descending order, then head selecting the top n records, then reseting the frame; will produce the top n frequent records
top = montyda... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3><strong>What are the Classes of Classes (Master Classes) of complaints?</strong></h3> | #Considering the top crimes
#copy
top_classes_top = top
#Creation of a Master Class
top_classes_top['Master Class'] = 0
aux = top_classes_top['Master Class'].astype(float,copy=True)
top_classes_top['Master Class'] = aux
top_classes_top['Master Class'] = top_classes_top['Class']/100
top_classes_top['Master Class'] = t... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h4>Describing 'Master Classes'</h4> | #Inserting the description of the Master Classes
top_classes_top['Master Class Description'] =''
top_classes_top[top_classes_top['Master Class'] == 600]
test_top = top_classes_top
test_top.loc[(test_top['Master Class'] == 600),'Master Class Description'] = 'LARCENY'
test_top.loc[(test_top['Master Class'] == 2900),... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>Could we categorize the types of crimes in violent or not?</h3>
According to wikipedia (https://en.wikipedia.org/wiki/Violent_crime) include but are not limited to this list of crimes: Typically, violent criminals includes aircraft hijackers, bank robbers, muggers, burglars, terrorists, carjackers, rapists, kidnap... | test_top['Violent crime'] = False
test_top.loc[(test_top['Master Class'] == 500),'Violent crime'] = True
test_top.loc[(test_top['Master Class'] == 800),'Violent crime'] = True
test_top.loc[(test_top['Master Class'] == 700),'Violent crime'] = True
test_top.sort_values(['Violent crime', 'frequency'], ascending=False... | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
Acording to the data, almost 80% of the crimes selected from the total of crimes, the violent crimes are only | value_percentage = test_top[test_top['Violent crime'] == True]['frequency'].sum()
value_percentage = round(value_percentage,2)
print(str(value_percentage) + '% of the total crimes') | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>Wich period (morning, afternoon, night) of the day that most complaints occur</h3> | #Considering the top crimes
day_process = montydata
| EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>Wich day of the week that most complaints occur</h3> | #Considering the top crimes | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>Wich month of the years that most complaints occur</h3> | #Considering the top crimes | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>These complainsts are related with holidays?</h3> | #Considering the top crimes | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
<h3>What period of time (time of day/day of the week/month of the year) has correlation with the type of complaint</h3> | #Considering the top crimes | EEC2006/1_CrimeProject/Finding crime patterns in Montgomery County-Copy1.ipynb | marco-olimpio/ufrn | gpl-3.0 |
Pure-Python ADMM Implementation
The code below is a direct Python port of the reference MATLAB implementation in Reference[1]. | from numpy.linalg import inv, norm
def objective(P, q, r, x):
"""Return the value of the Standard form QP using the current value of x."""
return 0.5 * np.dot(x, np.dot(P, x)) + np.dot(q, x) + r
def qp_admm(P, q, r, lb, ub,
max_iter=1000,
rho=1.0,
alpha=1.2, ... | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
QP Solver using CVXPY
For comparison, we also implement QP solver using cvxpy. | import cvxpy as cvx
def qp_cvxpy(P, q, r, lb, ub,
max_iter=1000,
atol=1e-4,
rtol=1e-2):
n = P.shape[0]
# The variable we want to solve for
x = cvx.Variable(n)
constraints = [x >= cvx.Constant(lb), x <= cvx.Constant(ub)]
# Construct the QP expression us... | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Generate Optimal Portfolio Holdings
In this section, we define a helper function to load the one of the five asset returns datasets from OR library (Reference [2]). The data are available by requesting filenames port[1-5]. Each file contains a progressively larger set of asset returns, standard deviations of returns an... | import requests
from statsmodels.stats.moment_helpers import corr2cov
from functools import lru_cache
@lru_cache(maxsize=5)
def get_cov(filename):
url = r'http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/{}.txt'.format(filename)
data = requests.get(url).text
lines = [line.strip() for line in data.split(... | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Set up the Portfolio Optimization problem as a QP | from numpy.random import RandomState
rng = RandomState(0)
P = get_cov('port1')
n = P.shape[0]
alphas = rng.uniform(-0.4, 0.4, size=n)
q = -alphas
ub = np.ones_like(q)
lb = np.zeros_like(q)
r = 0 | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Using ADMM | %%time
x_opt_admm, history = qp_admm(P, q, r, lb, ub)
fig, ax = plt.subplots(history.shape[1], 1, figsize=(10, 8))
ax = history.plot(subplots=True, ax=ax, rot=0) | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Using CVXPY | %%time
x_opt_cvxpy = qp_cvxpy(P, q, r, lb, ub) | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Optimal Holdings Comparison | holdings = pd.DataFrame(np.column_stack([x_opt_admm, x_opt_cvxpy]), columns=['opt_admm', 'opt_cvxpy'])
fig, ax = plt.subplots(1, 1, figsize=(12, 4))
ax = holdings.plot(kind='bar', ax=ax, rot=0)
labels = ax.set(xlabel='Assets', ylabel='Holdings') | simple_implementations/qp_admm.ipynb | dipanjank/ml | gpl-3.0 |
Let's take a look at our base (content) image and our style reference image | from IPython.display import Image, display
display(Image(base_image_path))
display(Image(style_reference_image_path))
| examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
Image preprocessing / deprocessing utilities |
def preprocess_image(image_path):
# Util function to open, resize and format pictures into appropriate tensors
img = keras.preprocessing.image.load_img(
image_path, target_size=(img_nrows, img_ncols)
)
img = keras.preprocessing.image.img_to_array(img)
img = np.expand_dims(img, axis=0)
i... | examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
Compute the style transfer loss
First, we need to define 4 utility functions:
gram_matrix (used to compute the style loss)
The style_loss function, which keeps the generated image close to the local textures
of the style reference image
The content_loss function, which keeps the high-level representation of the
genera... | # The gram matrix of an image tensor (feature-wise outer product)
def gram_matrix(x):
x = tf.transpose(x, (2, 0, 1))
features = tf.reshape(x, (tf.shape(x)[0], -1))
gram = tf.matmul(features, tf.transpose(features))
return gram
# The "style loss" is designed to maintain
# the style of the reference i... | examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
Next, let's create a feature extraction model that retrieves the intermediate activations
of VGG19 (as a dict, by name). | # Build a VGG19 model loaded with pre-trained ImageNet weights
model = vgg19.VGG19(weights="imagenet", include_top=False)
# Get the symbolic outputs of each "key" layer (we gave them unique names).
outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])
# Set up a model that returns the activation... | examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
Finally, here's the code that computes the style transfer loss. | # List of layers to use for the style loss.
style_layer_names = [
"block1_conv1",
"block2_conv1",
"block3_conv1",
"block4_conv1",
"block5_conv1",
]
# The layer to use for the content loss.
content_layer_name = "block5_conv2"
def compute_loss(combination_image, base_image, style_reference_image):
... | examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
Add a tf.function decorator to loss & gradient computation
To compile it, and thus make it fast. |
@tf.function
def compute_loss_and_grads(combination_image, base_image, style_reference_image):
with tf.GradientTape() as tape:
loss = compute_loss(combination_image, base_image, style_reference_image)
grads = tape.gradient(loss, combination_image)
return loss, grads
| examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
The training loop
Repeatedly run vanilla gradient descent steps to minimize the loss, and save the
resulting image every 100 iterations.
We decay the learning rate by 0.96 every 100 steps. | optimizer = keras.optimizers.SGD(
keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=100.0, decay_steps=100, decay_rate=0.96
)
)
base_image = preprocess_image(base_image_path)
style_reference_image = preprocess_image(style_reference_image_path)
combination_image = tf.Variable(preprocess... | examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
After 4000 iterations, you get the following result: | display(Image(result_prefix + "_at_iteration_4000.png"))
| examples/generative/ipynb/neural_style_transfer.ipynb | keras-team/keras-io | apache-2.0 |
1. Create a Doc object from the file owlcreek.txt<br>
HINT: Use with open('../TextFiles/owlcreek.txt') as f: | # Enter your code here:
with open('../TextFiles/owlcreek.txt') as f:
doc = nlp(f.read())
# Run this cell to verify it worked:
doc[:36] | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
3. How many sentences are contained in the file?<br>HINT: You'll want to build a list first! | sents = [sent for sent in doc.sents]
len(sents) | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
4. Print the second sentence in the document<br> HINT: Indexing starts at zero, and the title counts as the first sentence. | print(sents[1].text) | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
5. For each token in the sentence above, print its text, POS tag, dep tag and lemma<br>
CHALLENGE: Have values line up in columns in the print output. | # NORMAL SOLUTION:
for token in sents[1]:
print(token.text, token.pos_, token.dep_, token.lemma_)
# CHALLENGE SOLUTION:
for token in sents[1]:
print(f'{token.text:{15}} {token.pos_:{5}} {token.dep_:{10}} {token.lemma_:{15}}') | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
6. Write a matcher called 'Swimming' that finds both occurrences of the phrase "swimming vigorously" in the text<br>
HINT: You should include an 'IS_SPACE': True pattern between the two words! | # Import the Matcher library:
from spacy.matcher import Matcher
matcher = Matcher(nlp.vocab)
# Create a pattern and add it to matcher:
pattern = [{'LOWER': 'swimming'}, {'IS_SPACE': True, 'OP':'*'}, {'LOWER': 'vigorously'}]
matcher.add('Swimming', None, pattern)
# Create a list of matches called "found_matches" an... | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
7. Print the text surrounding each found match | print(doc[1265:1290])
print(doc[3600:3615]) | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
EXTRA CREDIT:<br>Print the sentence that contains each found match | for sent in sents:
if found_matches[0][1] < sent.end:
print(sent)
break
for sent in sents:
if found_matches[1][1] < sent.end:
print(sent)
break | nlp/UPDATED_NLP_COURSE/01-NLP-Python-Basics/07-NLP-Basics-Assessment-Solution.ipynb | rishuatgithub/MLPy | apache-2.0 |
Downloading and ranking structures
Methods
<div class="alert alert-warning">
**Warning:**
Downloading all PDBs takes a while, since they are also parsed for metadata. You can skip this step and just set representative structures below if you want to minimize the number of PDBs downloaded.
</div> | # Download all mapped PDBs and gather the metadata
my_gempro.pdb_downloader_and_metadata()
my_gempro.df_pdb_metadata.head(2)
# Set representative structures
my_gempro.set_representative_structure()
my_gempro.df_representative_structures.head()
# Looking at the information saved within a gene
my_gempro.genes.get_by_id... | docs/notebooks/GEM-PRO - SBML Model.ipynb | nmih/ssbio | mit |
Conversion of the Data into OxCal-usable Form | df = pd.read_csv("https://raw.githubusercontent.com/dirkseidensticker/aDRAC/master/data/aDRAC.csv", encoding='utf8')
display(df.head()) | Python/aDRACtoOxCal.ipynb | dirkseidensticker/CARD | mit |
Choosing only the first five entries as subsample: | df_sub = df.head() | Python/aDRACtoOxCal.ipynb | dirkseidensticker/CARD | mit |
OxCal-compliant output: | print('''Plot()
{''')
for index, row in df_sub.iterrows():
print('R_Date("', row['SITE'],'/', row['FEATURE'], '-', row['LABNR'],'",', row['C14AGE'],',', row['C14STD'],');')
print('};') | Python/aDRACtoOxCal.ipynb | dirkseidensticker/CARD | mit |
As we can see these two documents are not very similar, at least in terms of their 3-gram shingle Jaccard similarity. That aside the problem with these shingles is that they do not allow us to compute the similarities of large numbers of documents very easily, we have to do an all pairs comparison. To get around that w... | from lsh import minhash
for _ in range(5):
hasher = minhash.MinHasher(seeds=100, char_ngram=5)
fingerprint0 = hasher.fingerprint('Lorem Ipsum dolor sit amet'.encode('utf8'))
fingerprint1 = hasher.fingerprint('Lorem Ipsum dolor sit amet is how dummy text starts'.encode('utf8'))
print(sum(fingerprint0[i]... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
Increasing the length of the fingerprint from $k=100$ to $k=1000$ reduces the variance between random initialisations of the minhasher. | for _ in range(5):
hasher = minhash.MinHasher(seeds=1000, char_ngram=5)
fingerprint0 = hasher.fingerprint('Lorem Ipsum dolor sit amet'.encode('utf8'))
fingerprint1 = hasher.fingerprint('Lorem Ipsum dolor sit amet is how dummy text starts'.encode('utf8'))
print(sum(fingerprint0[i] in fingerprint1 for i i... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
Some duplicate items are present in the corpus so let's see what happens when we apply LSH to it. First a helper function that takes a file pointer and some parameters for minhash and LSH and then finds duplicates. | import itertools
from lsh import cache, minhash # https://github.com/mattilyra/lsh
# a pure python shingling function that will be used in comparing
# LSH to true Jaccard similarities
def shingles(text, char_ngram=5):
return set(text[head:head + char_ngram] for head in range(0, len(text) - char_ngram))
def jacc... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
Then run through some data adding documents to the LSH cache | hasher = minhash.MinHasher(seeds=100, char_ngram=5, hashbytes=4)
lshcache = cache.Cache(bands=10, hasher=hasher)
# read in the data file and add the first 100 documents to the LSH cache
with open('/usr/local/scratch/data/rcv1/headline.text.txt', 'rb') as fh:
feed = itertools.islice(fh, 100)
for line in feed:
... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
candidate_pairs now contains a bunch of document IDs that may be duplicates of each other | candidate_pairs | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
Now let's run LSH on a few different parameter settings and see what the results look like. To save some time I'm only using the first 1000 documents. | num_candidates = []
bands = [2, 5, 10, 20]
for num_bands in bands:
with open('/usr/local/scratch/data/rcv1/headline.text.txt', 'rb') as fh:
feed = itertools.islice(fh, 1000)
candidates = candidate_duplicates(feed, char_ngram=5, seeds=100, bands=num_bands, hashbytes=4)
num_candidates.append(l... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
So the more promiscuous [4] version (20 bands per fingerprint) finds many more candidate pairs than the conservative 2 bands model. The first implication of this difference is that it leads to you having to do more comparisons to find the real duplicates. Let's see what that looks like in practice.
We'll slightly modif... | def candidate_duplicates(document_feed, char_ngram=5, seeds=100, bands=5, hashbytes=4):
char_ngram = 5
sims = []
hasher = minhash.MinHasher(seeds=seeds, char_ngram=char_ngram, hashbytes=hashbytes)
if seeds % bands != 0:
raise ValueError('Seeds has to be a multiple of bands. {} % {} != 0'.format(... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
So LSH with 20 bands indeed finds a lot of candidate duplicates (111 out of 1000), some of which - for instance (3256, 3186) above - are not all that similar. Let's see how many LSH missed given some similarity threshold. | sims_all = np.zeros((1000, 1000), dtype=np.float64)
for i, line in enumerate(lines):
for j in range(i+1, len(lines)):
shingles_a = shingles(lines[i])
shingles_b = shingles(lines[j])
jaccard_sim = jaccard(shingles_a, shingles_b)
# similarities are symmetric so we only care ab... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
That seems pretty well inline with the <a href="#bands_rows">figure</a> showing how setting bands and rows affects the probability of finding similar documents. So we're doing quite well in terms of the true positives, what about the false positives? 27 pairs of documents from the ones found were true positives, so the... | # preprocess RCV1 to be contained in a single file
import glob, zipfile, re
import xml.etree.ElementTree as ET
files = glob.glob('../data/rcv1/xml/*.zip')
with open('../data/rcv1/headline.text.txt', 'wb') as out:
for f in files:
zf = zipfile.ZipFile(f)
for zi in zf.namelist():
fh = zf.o... | examples/Introduction.ipynb | mattilyra/suckerpunch | lgpl-3.0 |
Data Exploration | star_wars = pd.read_csv('star_wars.csv', encoding="ISO-8859-1")
star_wars.head()
star_wars.columns | Star Wars survey/Star Wars survey.ipynb | frankbearzou/Data-analysis | mit |
Data Cleaning
Remove invalid first column RespondentID which are NaN. | star_wars = star_wars.dropna(subset=['RespondentID']) | Star Wars survey/Star Wars survey.ipynb | frankbearzou/Data-analysis | mit |
Change the second and third columns. | star_wars['Do you consider yourself to be a fan of the Star Wars film franchise?'].isnull().value_counts()
star_wars['Have you seen any of the 6 films in the Star Wars franchise?'].value_counts() | Star Wars survey/Star Wars survey.ipynb | frankbearzou/Data-analysis | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.