markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Generating Batches Here's a generator function that returns batches of input and target data for our model, using the `get_target` function from above. The idea is that it grabs `batch_size` words from a words list. Then for each of those batches, it gets the target words in a window. | def get_batches(words, batch_size, window_size=5):
''' Create a generator of word batches as a tuple (inputs, targets) '''
n_batches = len(words)//batch_size
# only full batches
words = words[:n_batches*batch_size]
for idx in range(0, len(words), batch_size):
x, y = [], []
... | x
[0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
y
[1, 0, 2, 3, 0, 1, 3, 0, 1, 2]
| MIT | word2vec-embeddings/Negative_Sampling_Exercise.ipynb | sonalagrawal7/DeepLearning-nanodegree-exercises |
--- ValidationHere, I'm creating a function that will help us observe our model as it learns. We're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them using the cosine similarity: $$\mathrm{similarity} = \cos(\theta) = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b... | def cosine_similarity(embedding, valid_size=16, valid_window=100, device='cpu'):
""" Returns the cosine similarity of validation words with words in the embedding matrix.
Here, embedding should be a PyTorch embedding module.
"""
# Here we're calculating the cosine similarity between some random... | _____no_output_____ | MIT | word2vec-embeddings/Negative_Sampling_Exercise.ipynb | sonalagrawal7/DeepLearning-nanodegree-exercises |
--- SkipGram modelDefine and train the SkipGram model. > You'll need to define an [embedding layer](https://pytorch.org/docs/stable/nn.htmlembedding) and a final, softmax output layer.An Embedding layer takes in a number of inputs, importantly:* **num_embeddings** – the size of the dictionary of embeddings, or how many... | import torch
from torch import nn
import torch.optim as optim
class SkipGramNeg(nn.Module):
def __init__(self, n_vocab, n_embed, noise_dist=None):
super().__init__()
self.n_vocab = n_vocab
self.n_embed = n_embed
self.noise_dist = noise_dist
# define embeddin... | _____no_output_____ | MIT | word2vec-embeddings/Negative_Sampling_Exercise.ipynb | sonalagrawal7/DeepLearning-nanodegree-exercises |
TrainingBelow is our training loop, and I recommend that you train on GPU, if available. | device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Get our noise distribution
# Using word frequencies calculated earlier in the notebook
word_freqs = np.array(sorted(freqs.values(), reverse=True))
unigram_dist = word_freqs/word_freqs.sum()
noise_dist = torch.from_numpy(unigram_dist**(0.75)/np.sum(unigram_dist*... | Epoch: 1/3
Loss: 6.543435573577881
but | angel, democratic, some, eagles, unrest
after | upgrades, the, yau, sam, commissioning
one | the, and, six, british, four
years | forum, afro, stole, guardian, called
not | oldest, arizona, vdash, freshwater, of
such | painter, regardless, creature, uc, jews
when | lukoff, japa... | MIT | word2vec-embeddings/Negative_Sampling_Exercise.ipynb | sonalagrawal7/DeepLearning-nanodegree-exercises |
Visualizing the word vectorsBelow we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out [this post from Christopher Olah](http://colah.github.io/posts/2014-10-Visualizing-MNIST/) to lear... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
# getting embeddings from the embedding layer of our model, by name
embeddings = model.in_embed.weight.to('cpu').data.numpy()
viz_words = 380
tsne = TSNE()
embed_tsne = tsne.fit_transform... | _____no_output_____ | MIT | word2vec-embeddings/Negative_Sampling_Exercise.ipynb | sonalagrawal7/DeepLearning-nanodegree-exercises |
Some keys are used to signal special characters. Namely,- The ENTER key is represented as 0.- The shift key for capitalization is represented as ^.- The backspace key is represented as <.- All the remaining characters not found in the valid keys are encoded as .- Empty keys will contain the character _. | len(keys), keys | _____no_output_____ | MIT | notebooks/1.0-jf-en-test.ipynb | joaopfonseca/dssgsummit2020-challenge |
The most basic approaches | Counter(corpus).most_common()[:10]
baseline = ''.join([i[0] for i in Counter(corpus).most_common()])
baseline = baseline + ''.join([i for i in keys if i not in baseline]) + ' T'
baseline
shuffled = list(baseline)
rng.shuffle(shuffled)
anthony = 'EINOA TCGVDURL<^SWH_Z__XJQFPBMY,#.0K?'
check_keyboard(baseline, keys)
c... | Shuffled cost: 233432.54787591402
Original keys cost: 215629.56595268694
Baseline cost: 170178.49650661062
Anthony Carbajal's solution: 158733.94185884856
| MIT | notebooks/1.0-jf-en-test.ipynb | joaopfonseca/dssgsummit2020-challenge |
First attempt with GA | keys_list = list(keys)
def evaluate(individual):
"""
Computes the cost for each individual.
"""
try:
check_keyboard(individual, keys)
return [compute_cost(''.join(list(individual)), corpus)]
except AssertionError:
return [np.inf]
def mutFlip(ind1, ind2):
"""Execute a tw... | _____no_output_____ | MIT | notebooks/1.0-jf-en-test.ipynb | joaopfonseca/dssgsummit2020-challenge |
Manipulating the command line | import os
import subprocess
import shutil | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
OS | # See contents of directory
os.listdir('/mnt/GEN2212/')
# Loop over objects in directory
for obj in os.listdir('/mnt/GEN2212/'):
# See if it is a directory
if os.path.isdir('/mnt/GEN2212/' + obj):
print("Directory:\t", obj)
else:
print("File:\t", obj)
# Acces enviroment variables
os.environ[... | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
Subprocess The cell below only works in jupyter | !ls -al /mnt/GEN2212/ | total 27945
drwxrwx--- 11 root CEREGE_GEN2212 12 Apr 8 10:47 .
drwxr-xr-x 3 root root 4096 Sep 21 2018 ..
drwxr-x--x 18 apohl CEREGE_GEN2212 20 Feb 26 10:09 GEN2212.apohl
drwxr-xr-x 10 asarr CEREGE_GEN2212 20 May 5 17:51 GEN2212.asarr
drwxr-x--x 2 atoumoulin CE... | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
A Few libraries exist:- os.popen- sys.?- subprocessHowever subprocess seems to be the most built out for "complex" tasks.To get the results use `stdout=subprocess.PIPE` then `output.stdout.readlines()` | output = subprocess.Popen(['ls', '-al', '/mnt/GEN2212'], stdout=subprocess.PIPE)
lines = output.stdout.readlines()
lines | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
We can then manipulate the output like strings to get info | for line in lines:
line = line.decode('utf-8')
if "wbanfield" in line:
print(line)
line = line.split(" ")
line = [obj for obj in line if len(obj) > 0]
print(line)
perm, uid, user, group, day, month, _, time, directory = line
perm
user | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
`.wait()` waits for a process to finish before continuing to the next one.`cwd` argument defines the directory from which the command is executed | proc1 = subprocess.Popen(["sleep", "2"], cwd="/mnt/GEN2212").wait()
proc2 = subprocess.Popen(["sleep", "3"], cwd="/mnt").wait() | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
File manipulation- 'r' -> read only- 'a' -> create if doesn't exist else append- 'w' -> write this overwrites the file if it exists | with open("ferret.jnl", "r") as f:
print("\n".join(f.readlines()))
with open("dummy.txt", 'w') as f:
print(f"User : {user} owns the Folder {directory}")
f.write(f"User : {user} owns the Folder {directory}") | User : wbanfield owns the Folder GEN2212.wbanfield
| MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
Shutil | # Remove all objects under given directory -> equivalent to rm -rf
shutil.rmtree("DIRECTORY")
# Copy files (and folders?)
shutil.copy2(source, dest) | _____no_output_____ | MIT | Notebooks/06_Manipulating_command_line/Command_line.ipynb | Anthogr/Snakes-in-Space |
Problem StatementCustomer churn and engagement has become one of the top issues for most banks. It costs significantly more to acquire new customers than retain existing. It is of utmost important for a bank to retain its customers. We have a data from a MeBank (Name changed) which has a data of 7124 customers. In t... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
churn=pd.read_csv("Churn_Modelling.csv") | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Inspect the data | churn.head()
churn.info() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Age and Balance variable has numeric data but data type is object. It appears some special character is present in this variable. Also there are missing values for some variables. EDA Removing unwanted variables | # remove the variables and check the data for the 10 rows
churn.head(10) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Checking dimensions after removing unwanted variables, Summary | churn.describe(include="all")
churn.shape | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Proportion of observations in Target classes | # Get the proportions
| _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Checking for Missing values | # Are there any missing values ?
| _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There are some missing values Checking for inconsistencies in Balance and Age variable | churn.Balance.sort_values() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There are 3 cases where '?' is present, and 3 cases where missing values are present for Balance variable. Summary also proves the count of missing variables. To confirm on the count of ? , running value_counts() | churn.Balance.value_counts()
churn[churn.Balance=="?"] | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
This confirms there are 3 cases having ? | churn.Age.value_counts().sort_values() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There is 1 case where ? is present Replacing ? as Nan in Age and Balance variable | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba | |
Verifying count of missing values for Age and Balance variable below: | churn.Balance.isnull().sum()
churn.Age.isnull().sum() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Imputing missing values | sns.boxplot(churn['Credit Score']) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
As Outliers are present in the "Credit Score", so we impute the null values by median | sns.boxplot(churn['Tenure'])
sns.boxplot(churn['Estimated Salary']) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Substituting the mean value for all other numeric variables | for column in churn[['Credit Score', 'Tenure', 'Estimated Salary']]:
mean = churn[column].mean()
churn[column] = churn[column].fillna(mean)
churn.isnull().sum() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Converting Object data type into Categorical | for column in churn[['Geography','Gender','Has CrCard','Is Active Member']]:
if churn[column].dtype == 'object':
churn[column] = pd.Categorical(churn[column]).codes
churn.head()
churn.info() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Substituting the mode value for all categorical variables | for column in churn[['Geography','Gender','Has CrCard','Is Active Member']]:
mode = churn[column].mode()
churn[column] = churn[column].fillna(mode[0])
churn.isnull().sum() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Age and Balance are still not addressed. Getting the modal value | churn['Balance'].mode()
churn['Age'].mode() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Replacing nan with modal values, | churn['Balance']=churn['Balance'].fillna(3000)
churn['Age']=churn['Age'].fillna(37)
churn.isnull().sum() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There are no more missing values. | churn.info() | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Age and Balance are still object, which has to be converted Converting Age and Balance to numeric variables | churn['Age']=churn['Age'].astype(str).astype(int)
churn['Balance']=churn['Balance'].astype(str).astype(float) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Checking for Duplicates | # Are there any duplicates ?
dups = churn.duplicated()
print('Number of duplicate rows = %d' % (dups.sum()))
churn[dups] | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There are no Duplicates Checking for Outliers | plt.figure(figsize=(15,15))
churn[['Age','Balance','Credit Score', 'Tenure', 'Estimated Salary']].boxplot(vert=0) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Very small number of outliers are present, which is also not significant as it will not affect much on ANN Predictions Checking pairwise distribution of the continuous variables | import seaborn as sns
sns.pairplot(churn[['Age','Balance','Credit Score', 'Tenure', 'Estimated Salary']]) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Checking for Correlations | # construct heatmap with only continuous variables
plt.figure(figsize=(10,8))
sns.set(font_scale=1.2)
sns.heatmap(churn[['Age','Balance','Credit Score', 'Tenure', 'Estimated Salary']].corr(), annot=True) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
There is hardly any correlation between the variables Train Test Split | from sklearn.model_selection import train_test_split
#Extract x and y
#split data into 70% training and 30% test data
# Checking dimensions on the train and test data
print('x_train: ',x_train.shape)
print('x_test: ',x_test.shape)
print('y_train: ',y_train.shape)
print('y_test: ',y_test.shape) | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Scaling the variables | from sklearn.preprocessing import StandardScaler
#Initialize an object for StandardScaler
#Scale the training data
x_train
# Apply the transformation on the test data
x_test = sc.transform(x_test)
x_test | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Building Neural Network Model | clf = MLPClassifier(hidden_layer_sizes=100, max_iter=5000,
solver='sgd', verbose=True, random_state=21,tol=0.01)
# Fit the model on the training data
| _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Predicting training data | # use the model to predict the training data
y_pred =
| _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Evaluating model performance on training data | from sklearn.metrics import confusion_matrix,classification_report
confusion_matrix(y_train,y_pred)
print(classification_report(y_train, y_pred))
# AUC and ROC for the training data
# predict probabilities
probs = clf.predict_proba(x_train)
# keep probabilities for the positive outcome only
probs = probs[:, 1]
# calcul... | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Predicting Test Data and comparing model performance | y_pred = clf.predict(x_test)
confusion_matrix(y_test, y_pred)
print(classification_report(y_test, y_pred))
# AUC and ROC for the test data
# predict probabilities
probs = clf.predict_proba(x_test)
# keep probabilities for the positive outcome only
probs = probs[:, 1]
# calculate AUC
auc = roc_auc_score(y_test, probs)
... | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
Model Tuning through Grid Search **Below Code may take too much time.These values can be used instead {'hidden_layer_sizes': 500, 'max_iter': 5000, 'solver': 'adam', 'tol': 0.01}** | from sklearn.model_selection import GridSearchCV
param_grid = {
'hidden_layer_sizes': [100,200,300,500],
'max_iter': [5000,2500,7000,6000],
'solver': ['sgd','adam'],
'tol': [0.01],
}
nncl = MLPClassifier(random_state=1)
grid_search = GridSearchCV(estimator = nncl, param_grid = param_grid, cv = 10)
gr... | _____no_output_____ | MIT | M4 Data Mining/W4 Artificial Nural Network/Neural Networks - Churn Prediction - Student File Aug 6.ipynb | fborrasumh/greatlearning-pgp-dsba |
**Lab Session : Feature extraction II**Author: Vanessa Gómez Verdejo (http://vanessa.webs.tsc.uc3m.es/)Updated: 27/02/2017 (working with sklearn 0.18.1)In this lab session we are going to work with some of the kernelized extensions of most well-known feature extraction techniques: PCA, PLS and CCA.As in the previous n... | %matplotlib inline | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
*Part 2: Non linear feature selection* ** 2.0: Creating toy problem **The following code let you generate a bidimensional problem consisting of thee circles of data with different radius, each one associated to a different class. As expected from the geometry of the problem, the classification boundary is not linear... | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_circles
import matplotlib.pyplot as plt
np.random.seed(0)
X, Y = make_circles(n_samples=400, factor=.6, noise=.1)
... | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
** Part 2.1: Kernel PCA**To extend the previous PCA feature extraction approach to its non-linear version, we can use of [KernelPCA( )](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.KernelPCA.htmlsklearn.decomposition.KernelPCA) function. Let's start this section computing the different kernel... | ###########################################################
# TODO: Replace <FILL IN> with appropriate code
###########################################################
from sklearn.decomposition import PCA, KernelPCA
N_feat_max=2
# linear PCA
pca = PCA(n_components=N_feat_max)
pca.fit(X_train, Y_train)
P_train = pca.... | PCA and KPCA projections sucessfully computed
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Now, let's evaluate the discriminatory capability of the projected data (both linear and kernelized ones) feeding with them a linear SVM and measuring its accuracy over the test data. Complete the following to code to return in variables acc_test_lin and acc_test_kernel the SVM test accuracy using either the linear PCA... | ###########################################################
# TODO: Replace <FILL IN> with appropriate code
###########################################################
# Define SVM classifier
from sklearn import svm
clf = svm.SVC(kernel='linear')
# Train it using linear PCA projections and evaluate it
clf.fit(P_train... | 1 test passed.
1 test passed.
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Finally, let's analyze the transformation capabilities of the projected data using a KPCA vs. linear PCA plotting the resulting projected data for both training and test data sets.Just run the following cells to obtain the desired representation. | def plot_projected_data(data, label):
"""Plot the desired sample data assigning differenet colors according to their categories.
Only two first dimensions of data ar plot and only three different categories are considered.
Args:
data: data set to be plot (number data x dimensions).
la... | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Go to the first cell and modify the kernel parameter (for instance, set gamma to 10 or 100) and run the code again. What is it happening? Why? ** Part 2.2: Analyzing the influence of the kernel parameter**In the case of working with RBF kernel, the kernel width selection can be critical:* If gamma value is too high t... | ## Redefine the data partitions: creating a validation partition
# split training data into a training and validation set
X_train2, X_val, Y_train2, Y_val = train_test_split(X_train, Y_train, test_size=0.33)
# Normalizing the data
scaler = StandardScaler()
X_train2 = scaler.fit_transform(X_train2)
X_val = scaler.tran... | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Now let's evaluate the KPCA performance when different values of gamma are used. So, complete the below code in such a way that for each gamma value you can:* Train the KPCA and obtain the projections for the training, validation and test data.* Obtain the accuracies of a linear SVM over the validation and test partiti... | ###########################################################
# TODO: Replace <FILL IN> with appropriate code
###########################################################
from sklearn.decomposition import KernelPCA
from sklearn import svm
np.random.seed(0)
# Defining parameters
N_feat_max = 2
rang_g = [0.01, 0.05, 0.1, ... | 1 test passed.
1 test passed.
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Finally, just run the next code to train the final model with the selected gamma value and plot the projected data | # Train KPCA and project the data
pca_K = KernelPCA(n_components=N_feat_max, kernel="rbf", gamma=g_opt)
pca_K.fit(X_train2)
P_train_k = pca_K.transform(X_train2)
P_val_k = pca_K.transform(X_val)
P_test_k = pca_K.transform(X_test)
# Plot the projected data
plt.figure(figsize=(15, 5))
plt.subplot(1,3,1)
plt.title("Pr... | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
** Part 2.3: Kernel MVA approaches** Until now, we have only used the KPCA approach because is the only not linear feature extraction method that it is included in Scikit-Learn. However, if we compare linear and kernel versions of MVA approaches, we could extend any linear MVA approach to its kernelized version. In th... | ###########################################################
# TODO: Replace <FILL IN> with appropriate code
###########################################################
# Computing the kernel matrix
from sklearn.metrics.pairwise import rbf_kernel
g_value = 1
# Compute the kernel matrix (use the X_train matrix, before... | 1 test passed.
1 test passed.
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
After compute these kernel matrix, they have to be centered (in the same way that we remove the mean when we work over the input space). For this purpose, next code provides you the function center_K(). Use it properly to remove the mean of both K_tr and K_test matrix. | def center_K(K):
"""Center a kernel matrix K, i.e., removes the data mean in the feature space.
Args:
K: kernel matrix
"""
size_1,size_2 = K.shape;
D1 = K.sum(axis=0)/size_1
D2 = K.sum(axis=1)/size_2
E = D2.sum(axis=0)/size_1
K_n = K + n... | 1 test passed.
1 test passed.
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
** Alternative KPCA formulation **Complete the following code lines to obtain a KPCA implementaion using the linear PCA function and the kernel matrix as input data. Later, compare its result with that of the KPCA function. | ###########################################################
# TODO: Replace <FILL IN> with appropriate code
###########################################################
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
from sklearn import svm
# Defining parameters
N_feat_max = 2
## PCA... | Test accuracy with PCA with a kenel matrix as input: 0.946666666667
Test accuracy with KPCA: 0.96
| MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
** Alternative KPLS and KCCA formulations **Use the PLS and CCA methods with the kernel matrix to obtain no-linear (or kernelized) supervised feature extractors. | ###########################################################
# KCCA
###########################################################
from lib.mva import mva
# Defining parameters
N_feat_max = 2
## PCA method (to complete)
# 1. Train PCA with the kernel matrix and project the data
CCA = mva('CCA', N_feat_max)
CCA.fit(K_tr_... | _____no_output_____ | MIT | Feature Extraction/Feature Extraction II.ipynb | javiccano/Machine-Learning-Applications |
Practical 1: Sentiment Detection of Movie Reviews======================================== This practical concerns sentiment detection of movie reviews.In [this file](https://gist.githubusercontent.com/bastings/d47423301cca214e3930061a5a75e177/raw/5113687382919e22b1f09ce71a8fecd1687a5760/reviews.json) (80MB) you will fi... | # download sentiment lexicon
!wget https://gist.githubusercontent.com/bastings/d6f99dcb6c82231b94b013031356ba05/raw/f80a0281eba8621b122012c89c8b5e2200b39fd6/sent_lexicon
# download review data
!wget https://gist.githubusercontent.com/bastings/d47423301cca214e3930061a5a75e177/raw/5113687382919e22b1f09ce71a8fecd1687a5760... | 2000
0 NEG 29
Two/CD teen/JJ couples/NNS go/VBP to/TO a/DT church/NN party/NN ,/, drink/NN and/CC then/RB drive/NN ./.
1 NEG 11
Damn/JJ that/IN Y2K/CD bug/NN ./.
2 NEG 24
It/PRP is/VBZ movies/NNS like/IN these/DT that/WDT make/VBP a/DT jaded/JJ movie/NN viewer/NN thankful/JJ for/IN the/DT invention/NN of/IN the/DT Time... | MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Symbolic approach – sentiment lexicon (2pts)--------------------------------------------------------------------- **How** could one automatically classify movie reviews according to theirsentiment? If we had access to a **sentiment lexicon**, then there are ways to solvethe problem without using Machine Learning. One m... | #
# Given a line from the sentiment file
# ex. type=weaksubj len=1 word1=abandoned pos1=adj stemmed1=n priorpolarity=negative
# Returns a dictionary
# ex. {type: weaksubj, len: 1, word1: abandoned, pos1: adj, stemmed1: n, priorpolarity: negative}
#
def sentiment_line_to_dict(line):
dictionary = {}
words ... | Loaded the file!
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
This block contains the binary classification code | THRESHOLD = 8
#
# Given a review returns a list of all the words.
# note: all words are converted to lowercase
#
def get_words_of_review(review):
content = review['content']
words = []
for line in content:
for word_pair in line:
word = word_pair[0]
word_in_lowercase = ... | Binary classification accuracy: 68.45%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
If the sentiment lexicon also has information about the **magnitude** ofsentiment (e.g., *“excellent"* would have higher magnitude than*“good"*), we could take a more fine-grained approach by adding up allsentiment scores, and deciding the polarity of the movie review usingthe sign of the weighted score $S_{weighted}$.... | #
# Returns the weighted score of the word;
# it multiplies the original score of the word with the type (strong 3, neutral 2, or weak 1).
#
def get_weighted_score_of_word(word):
try:
score = sentiment_dict[word]
word_type = type_dict[word]
return word_type * score
except KeyError:
... | Magnitude classification accuracy: 68.80%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Optional: make a barplot of the two results. |
plt.bar("Binary", binary_accuracy)
plt.bar("Magnitude", magnitude_accuracy)
plt.ylabel("Accuracy in %")
plt.title("Accuracy of binary and magnitude classification")
plt.show()
| _____no_output_____ | MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Answering questions in statistically significant ways (1pt)------------------------------------------------------------- Does using the magnitude improve the results? Oftentimes, answering questions like this about the performance ofdifferent signals and/or algorithms by simply looking at the outputnumbers is not enoug... | from decimal import Decimal
from scipy.misc import comb
def sign_test(results_1, results_2):
"""test for significance
results_1 is a list of classification results (+ for correct, - incorrect)
results_2 is a list of classification results (+ for correct, - incorrect)
"""
ties, plus, minus = 0, 0, ... | /usr/local/Cellar/ipython/7.1.1/libexec/vendor/lib/python3.7/site-packages/ipykernel_launcher.py:27: DeprecationWarning: `comb` is deprecated!
Importing `comb` from scipy.misc is deprecated in scipy 1.0.0. Use `scipy.special.comb` instead.
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Using the Sign test**From now on, report all differences between systems using thesign test.** You can think about a change that you apply to one system, as a new system. You should report statistical testresults in an appropriate form – if there are several different methods(i.e., systems) to compare, tests can on... | #
# This class represents our bag of words. It stores the words in a dictionary in the following format:
# BOW = {
# 'cat': {
# 'POS': 3, # 3 positive occurences
# 'NEG': 1, # 1 negative occurences
# 'P_POS': 0.001 # probability of this word occuring in positive review
# 'P_NEG': 0.... | _____no_output_____ | MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
The following code block contains our BayesClassifier class. |
class BayesClassifier:
#
# use_smoothing: If True uses laplace smoothing with constant k=1
# use_stemming: If True uses stemming.
# n_grams: The number of features to use, e.g. if 2: both 1-grams and 2-grams are used as features.
# if 3: both 1-grams, 2-grams and 3-grams a... | Simple (no smoothing) bayes accuracy 49.50%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Bonus Questions) Would you consider accuracy to also be a good way to evaluate your classifier in a situation where 90% of your data instances are of positive movie reviews? (1pt)You can simulate this scenario by keeping the positive reviewsdata unchanged, but only using negative reviews cv000–cv089 fortraining, and ... | # Question is very vague, but here is what we think the data should look like:
# TRAIN
# 0 - 899 : positive reviews
# 0 - 89 : negative reviews
#
# TEST
# 900 - 999 : positive reviews
# 900 - 909 : negative reviews
#
bayes = BayesClassifier(False, False, 1)
train_indices = list(range(0,900))
train_sentiment = ... | Simple (no smoothing) bayes accuracy trained on 90% positive reviews 9.09%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
As you can see the classifier behaves badly now with only 9.09% accuracy. It predicts everything as a negative review. This is because it says very little negative reviews in the training data, and thus, each negative term in the training set will count 10 times more as each positive term in the training data. Meaning ... | bayes = BayesClassifier(True, False, 1)
train_indices = list(range(0,900))
test_indices = list(range(900, 1000))
smoothing_bayes_accuracy, smoothing_bayes_results = bayes.train_and_classify(train_indices, test_indices)
print("Smoothed bayes accuracy {0:.2f}%".format(smoothing_bayes_accuracy)) | Smoothed bayes accuracy 82.50%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Q3.3) Is the difference between non smoothed (Q3.1) and smoothed (Q3.2) statistically significant? (0.5pt) | p_value = sign_test(simple_bayes_results, smoothing_bayes_results)
print("p_value =", p_value) | the difference is significant
p_value = 0.000003547178174130642586494974890
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Cross-validationA serious danger in using Machine Learning on small datasets, with manyiterations of slightly different versions of the algorithms, is that weend up with Type III errors, also called the “testing hypothesessuggested by the data” errors. This type of error occurs when we makerepeated improvements to our... | #
# Returns test_indices, and train_indices according to the round robin split algorithm.
#
def round_robin_split_indices(n_split):
test_indices = []
train_indices = []
for i in range(0, 1000):
if i % 10 == n_split:
test_indices.append(i)
else:
train_indices.appe... | Progress 0%
Progress 10%
Progress 20%
Progress 30%
Progress 40%
Progress 50%
Progress 60%
Progress 70%
Progress 80%
Progress 90%
10-fold validation average accuracy for 10 folds: 81.70%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Q3.5) Write code to calculate and report variance, in addition to the final performance. (1pt)**Please report all future results using 10-fold cross-validation now(unless told to use the held-out test set).** | print("10-fold validation variance: {0:.2f}".format(smoothing_variance)) | 10-fold validation variance: 6.51
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Features, overfitting, and the curse of dimensionalityIn the Bag-of-Words model, ideally we would like each distinct word inthe text to be mapped to its own dimension in the output vectorrepresentation. However, real world text is messy, and we need to decideon what we consider to be a word. For example, is “`word`" d... | stemming_avg_accuracy, stemming_variance, stemming_results_kfold = do_kfold("BOTH", True, True)
print("10-fold stemming average accuracy {0:.2f}%".format(stemming_avg_accuracy)) | Progress 0%
Progress 10%
Progress 20%
Progress 30%
Progress 40%
Progress 50%
Progress 60%
Progress 70%
Progress 80%
Progress 90%
10-fold stemming average accuracy 81.45%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Q3.7): Is the difference between NB with smoothing and NB with smoothing+stemming significant? (0.5pt) | p_value = sign_test(stemming_results_kfold, smoothing_results_kfold)
print("p_value =", p_value) | /usr/local/Cellar/ipython/7.1.1/libexec/vendor/lib/python3.7/site-packages/ipykernel_launcher.py:27: DeprecationWarning: `comb` is deprecated!
Importing `comb` from scipy.misc is deprecated in scipy 1.0.0. Use `scipy.special.comb` instead.
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Q3.8: What happens to the number of features (i.e., the size of the vocabulary) when using stemming as opposed to (Q3.2)? (0.5pt)Give actual numbers. You can use the held-out training set to determine these. | bayes = BayesClassifier(False, False, 1)
bayes_stemming = BayesClassifier(False, True, 1)
train_indices = list(range(0, 900))
bow = bayes.train(train_indices, [])
bow_stemming = bayes_stemming.train(train_indices, [])
print("Number of words withouth stemming: {}".format(bow.get_n_unique_words()))
... | Number of words withouth stemming: 45348
Number of words with stemming: 32404
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Q3.9: Putting some word order back in (0.5+0.5pt=1pt)A simple way of retaining some of the wordorder information when using bag-of-words representations is to add **n-grams** features. Retrain your classifier from (Q3.4) using **unigrams+bigrams** and**unigrams+bigrams+trigrams** as features, and report accuracy and s... | bigram_avg_accuracy, bigram_variance, bigram_results_kfold = do_kfold(True, False, 2)
trigram_avg_accuracy, trigram_variance, trigram_results_kfold = do_kfold(True, False, 3)
print("Unigram average accuracy {0:.2f}%".format(smoothing_avg_accuracy))
print("Bigram average accuracy {0:.2f}%".format(bigram_avg_accuracy))
... | Improvement from unigrams to unigrams+bigrams
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Q3.10: How many features does the BoW model have to take into account now? (0.5pt)How does this number compare (e.g., linear, square, cubed, exponential) to the number of features at (Q3.8)? Use the held-out training set once again for this. | bayes_bigrams = BayesClassifier(False, False, 2)
bayes_trigrams = BayesClassifier(False, False, 3)
bayes_fourgrams = BayesClassifier(False, False, 4)
train_indices = list(range(0, 900))
bow_bigrams = bayes_bigrams.train(train_indices, [])
bow_trigrams = bayes_trigrams.train(train_indices, [])
print("Number of fea... | Number of features with unigrams: 45348
Number of features with bigrams: 471032
Number of features with trigrams: 1416686
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
As you can see the number of features goes from ~50,000 to ~500,000 to ~1,500,000 this shows that the increase in features is exponential Support Vector Machines (4pts) Though simple to understand, implement, and debug, onemajor problem with the Naive Bayes classifier is that its performancedeteriorates (becomes skewe... | from sklearn import preprocessing, model_selection, neighbors, svm
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC as SVC
from nltk.tokenize import TreebankWordTokenizer
#
## Returns test_indices, and train_indices according to the round robin split algorithm.
## adjusted ... | Progress 0%
Progress 10%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
More linguisticsNow add in part-of-speech features. You will find themovie review dataset has already been POS-tagged for you. Try toreplicate what Pang et al. were doing: (Q4.2) Replace your features with word+POS features, and report performance with the SVM. Does this help? Do cross validation and concatenate the ... | # What canges, when pos tags are taken into consideration as well?
svm_avg_accuracy_with_tags, svm_variance_with_tags, svm_results_kfold_with_tags = do_kfold_svm(tags=True)
print("10-fold average accuracy {0:.2f}%".format(svm_avg_accuracy_with_tags))
print("10-fold accuracy variance {0:.2f}%".format(svm_variance_wi... | Progress 0%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Q4.3) Discard all closed-class words from your data (keep only nouns (N*), verbs (V*), adjectives (J*) and adverbs (RB*)), and report performance. Does this help? Do cross validation and concatenate the predictions from all folds to compute the significance. Are the results significantly better than when we don't dis... | svm_avg_accuracy_without_closed, svm_variance_without_closed, svm_results_kfold_without_closed = do_kfold_svm(tags=True, without_closed=True)
print("10-fold average accuracy {0:.2f}%".format(svm_avg_accuracy_without_closed))
print("10-fold accuracy variance {0:.2f}%".format(svm_variance_without_closed))
# significan... | Progress 0%
Progress 10%
| MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
(Q5) Discussion (max. 500 words). (5pts)> Based on your experiments, what are the effective features and techniques in sentiment analysis? What information do different features encode?Why is this important? What are the limitations of these features and techniques? *Write your answer here in max. 500 words.*Discussi... | # Write your names and student numbers here:
# Dirk Hoekstra #12283878
# Philipp Lintl #12152498 | _____no_output_____ | MIT | Natural Language Processing 1/nlp1_v2.ipynb | PhilLint/Master |
Bank Account | class Bank_Account:
def __init__(self):
self.balance=0
print("YIEEE may sweldo na sya")
name = input("Enter your name: ")
print("")
AccountNumber = input("Enter your number: ")
print("Welcome Ian!")
def deposit(self):
amount=float(input("Enter amount to be deposited: "))
self.balance ... | Enter your name: Ian
Enter your number: 123456789
Welcome Ian!
YIEEE may sweldo na sya
Enter amount to be deposited: 1234
Amount Deposited: 1234.0
Net Available Balance= 1234.0
| Apache-2.0 | OOP_58003_LONG_QUIZ.ipynb | IanReyes2/OOP-58003 |
Passing Messages to Processes As with threads, a common use pattern for multiple processes is to divide a job up among several workers to run in parallel. Effective use of multiple processes usually requires some communication between them, so that work can be divided and results can be aggregated. A simple way to com... | import multiprocessing
class MyFancyClass:
def __init__(self, name):
self.name = name
def do_something(self):
proc_name = multiprocessing.current_process().name
print('Doing something fancy in {} for {}!'.format(
proc_name, self.name))
def worker(q):
obj = q.get()
... | Doing something fancy in Process-2 for Fancy Dan!
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
A more complex example shows how to manage several workers consuming data from a JoinableQueue and passing results back to the parent process. The poison pill technique is used to stop the workers. After setting up the real tasks, the main program adds one “stop” value per worker to the job queue. When a worker encount... | import multiprocessing
import time
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
def run(self):
proc_name = self.name
while Tr... | Creating 16 consumers
Consumer-5: 2 * 2
Consumer-3: 0 * 0
Consumer-6: 3 * 3
Consumer-8: 5 * 5
Consumer-9: 6 * 6
Consumer-4: 1 * 1
Consumer-11: 8 * 8
Consumer-18: 4 * 4
Consumer-16: Exiting
Consumer-12: 9 * 9
Consumer-17: Exiting
Consumer-7: 7 * 7
Consumer-14: Exiting
Consumer-15: Exiting
Consumer-10: Exiting
Consumer-1... | Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
Signaling between Processes The Event class provides a simple way to communicate state information between processes. An event can be toggled between set and unset states. Users of the event object can wait for it to change from unset to set, using an optional timeout value. | import multiprocessing
import time
def wait_for_event(e):
"""Wait for the event to be set before doing anything"""
print('wait_for_event: starting')
e.wait()
print('wait_for_event: e.is_set()->', e.is_set())
def wait_for_event_timeout(e, t):
"""Wait t seconds and then timeout"""
print('wait_... | wait_for_event: starting
wait_for_event: starting
wait_for_event_timeout: starting
main: waiting before calling Event.set()
wait_for_event_timeout: e.is_set()-> False
main: event is set
wait_for_event: e.is_set()-> True
wait_for_event: e.is_set()-> True
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
* When wait() times out it returns without an error. The caller is responsible for checking the state of the event using is_set().* a event.set() will set off all process that are waiting for this event Controlling Access to Resources In situations when a single resource needs to be shared between multiple processes, ... | import multiprocessing
import sys
def worker_with(lock, stream):
with lock:
stream.write('Lock acquired via with\n')
def worker_no_with(lock, stream):
lock.acquire()
try:
stream.write('Lock acquired directly\n')
finally:
lock.release()
lock = multiprocessing.Lock()
w = mult... | Lock acquired via with
Lock acquired directly
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
Synchronizing Operations Condition Condition objects can be used to synchronize parts of a workflow so that some run in parallel but others run sequentially, even if they are in separate processes. | import multiprocessing
import time
def stage_1(cond):
"""perform first stage of work,
then notify stage_2 to continue
"""
name = multiprocessing.current_process().name
print('Starting', name)
with cond:
print('{} done and ready for stage 2'.format(name))
cond.notify_all()
def... | Starting stage_2[1]
Starting stage_2[2]
Starting s1
s1 done and ready for stage 2
stage_2[2] running
stage_2[1] running
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
In this example, two process run the second stage of a job in parallel, but only after the first stage is done. Controlling Concurrent Access to Resources Sometimes it is useful to allow more than one worker access to a resource at a time, while still limiting the overall number. For example, a connection pool might s... | import random
import multiprocessing
import time
class ActivePool:
def __init__(self):
super(ActivePool, self).__init__()
self.mgr = multiprocessing.Manager()
self.active = self.mgr.list()
self.lock = multiprocessing.Lock()
def makeActive(self, name):
with self.lock:
... | Activating 0 now running ['0']
Activating 1 now running ['0', '1']
Activating 2 now running ['0', '1', '2']
Activating 3 now running ['1', '2', '3']
Now running ['1', '2', '3']
Now running ['1', '2', '3']
Activating 4 now running ['1', '2', '4']
Now running ['1', '2', '3']
Now running ['1', '2', '3']
Activating 5 now r... | Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
Managing Shared State In the previous example, the list of active processes is maintained centrally in the ActivePool instance via a special type of list object created by a Manager. The Manager is responsible for coordinating shared information state between all of its users. | import multiprocessing
import pprint
def worker(d, key, value):
d[key] = value
if __name__ == '__main__':
mgr = multiprocessing.Manager()
d = mgr.dict()
jobs = [
multiprocessing.Process(
target=worker,
args=(d, i, i * 2),
)
for i in range(10)
]
... | Results: {0: 0, 1: 2, 3: 6, 2: 4, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
By creating the list through the manager, it is shared and updates are seen in all processes. Dictionaries are also supported. Shared Namespaces In addition to dictionaries and lists, a Manager can create a shared Namespace. | import multiprocessing
def producer(ns, event):
ns.value = 'This is the value'
event.set()
def consumer(ns, event):
try:
print('Before event: {}'.format(ns.value))
except Exception as err:
print('Before event, error:', str(err))
event.wait()
print('After event:', ns.value)
... | Before event, error: 'Namespace' object has no attribute 'value'
After event: This is the value
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
Any named value added to the Namespace is visible to all of the clients that receive the Namespace instance. **It is important to know that updates to the contents of mutable values in the namespace are not propagated automatically.** | import multiprocessing
def producer(ns, event):
# DOES NOT UPDATE GLOBAL VALUE!
ns.my_list.append('This is the value')
event.set()
def consumer(ns, event):
print('Before event:', ns.my_list)
event.wait()
print('After event :', ns.my_list)
if __name__ == '__main__':
mgr = multiprocessin... | Before event: []
After event : []
| Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
Process Pools The Pool class can be used to manage a fixed number of workers for simple cases where the work to be done can be broken up and distributed between workers independently. The return values from the jobs are collected and returned as a list. The pool arguments include the number of processes and a function... | import multiprocessing
def do_calculation(data):
return data * 2
def start_process():
print('Starting', multiprocessing.current_process().name)
if __name__ == '__main__':
inputs = list(range(10))
print('Input :', inputs)
builtin_outputs = map(do_calculation, inputs)
print('Built-in:', [... | Input : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Built-in: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Starting ForkPoolWorker-87
Starting ForkPoolWorker-86
Starting ForkPoolWorker-85
Starting ForkPoolWorker-88
Starting ForkPoolWorker-89
Starting ForkPoolWorker-90
Starting ForkPoolWorker-91
Starting ForkPoolWorker-92
Starting ForkPool... | Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
By default, Pool creates a fixed number of worker processes and passes jobs to them until there are no more jobs. Setting the maxtasksperchild parameter tells the pool to restart a worker process after it has finished a few tasks, preventing long-running workers from consuming ever more system resources. | import multiprocessing
def do_calculation(data):
return data * 2
def start_process():
print('Starting', multiprocessing.current_process().name)
if __name__ == '__main__':
inputs = list(range(10))
print('Input :', inputs)
builtin_outputs = map(do_calculation, inputs)
print('Built-in:', b... | Input : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Built-in: <map object at 0x7f430c35dbe0>
Starting ForkPoolWorker-101
Starting ForkPoolWorker-102
Starting ForkPoolWorker-103
Starting ForkPoolWorker-104
Starting ForkPoolWorker-105
Starting ForkPoolWorker-106
Starting ForkPoolWorker-107
Starting ForkPoolWorker-108
Starting ForkP... | Apache-2.0 | concurrency/multiprocessing/Passing_Messages_to_Processes.ipynb | scotthuang1989/Python-3-Module-of-the-Week |
End-to-end quantum chemistry VQE using Qu & Co ChemistryIn this tutorial we show how to solve the groundstate energy of a hydrogen molecule using VQE, as a function of the spacing between the atoms of the molecule. For a more detailed discussion on MolecularData generation or VQE settings, please refer to our other tu... | from openfermion.hamiltonians import MolecularData
from qucochemistry.vqe import VQEexperiment
from openfermionpyscf import run_pyscf
import numpy as np
#H2 spacing
spacing =np.array([0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6,0.7,0.74,0.75,0.8,0.85,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0])
M=len(sp... | _____no_output_____ | Apache-2.0 | examples/Tutorial_Disassociation_curve_end_to_end.ipynb | yaoyongxin/qucochemistry |
We compare the results for 5 different strategies: classical HF, CCSD, and FCI, with a quantum unitary variant of CCSD, called UCCSD and its optimized version. In other words, we calculate the Hamiltonian expectation value for a wavefunction which was propagated by a UCCSD ansatz with CCSD amplitudes. Then we initiate ... | %matplotlib notebook
import matplotlib.pyplot as plt
plt.figure()
plt.plot(spacing,E_hf,label='HF energy')
plt.plot(spacing,E_ccsd,label='CCSD energy')
plt.plot(spacing,E_uccsd,label='UCCSD energy (guess)')
plt.plot(spacing,E_uccsd_opt,label='UCCSD energy (optim)')
plt.plot(spacing,E_fci,label='FCI energy')
plt.xlabe... | _____no_output_____ | Apache-2.0 | examples/Tutorial_Disassociation_curve_end_to_end.ipynb | yaoyongxin/qucochemistry |
Random Forest Project For this project we will be exploring publicly available data from [LendingClub.com](www.lendingclub.com). Lending Club connects people who need money (borrowers) with people who have money (investors). Hopefully, as an investor you would want to invest in people who showed a profile of having a ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline | _____no_output_____ | MIT | Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb | KhushMody/Ds-Algo-HacktoberFest |
Get the Data** Use pandas to read loan_data.csv as a dataframe called loans.** | loans = pd.read_csv('loan_data.csv') | _____no_output_____ | MIT | Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb | KhushMody/Ds-Algo-HacktoberFest |
** Check out the info(), head(), and describe() methods on loans.** | loans.info()
loans.describe()
loans.head() | _____no_output_____ | MIT | Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb | KhushMody/Ds-Algo-HacktoberFest |
Exploratory Data Analysis** Create a histogram of two FICO distributions on top of each other, one for each credit.policy outcome.** | plt.figure(figsize=(10,6))
loans[loans['credit.policy']==1]['fico'].hist(alpha=0.5,bins=30,color='blue',label='Credit.Policy=1')
loans[loans['credit.policy']==0]['fico'].hist(alpha=0.5,bins=30,color='red',label='Credit.Policy=0')
plt.legend()
plt.xlabel('FICO') | _____no_output_____ | MIT | Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb | KhushMody/Ds-Algo-HacktoberFest |
** Create a similar figure, except this time select by the not.fully.paid column.** | plt.figure(figsize=(10,6))
loans[loans['not.fully.paid']==1]['fico'].hist(alpha=0.5,bins=30,color='blue',label='Credit.Policy=1')
loans[loans['not.fully.paid']==0]['fico'].hist(alpha=0.5,bins=30,color='red',label='Credit.Policy=0')
plt.legend()
plt.xlabel('FICO') | _____no_output_____ | MIT | Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb | KhushMody/Ds-Algo-HacktoberFest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.