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 |
|---|---|---|---|---|---|
Next, let’s build the dictionary to convert the index to word for target and source vocabulary: Inference Model Encoder Inference: | # encoder inference
latent_dim=500
#/content/gdrive/MyDrive/Text Summarizer/
#load the model
model = models.load_model("Text_Summarizer.h5")
#construct encoder model from the output of 6 layer i.e.last LSTM layer
en_outputs,state_h_enc,state_c_enc = model.layers[6].output
en_states=[state_h_enc,state_c_enc]
#add inpu... | _____no_output_____ | MIT | text-summarization-attention-mechanism.ipynb | buddhadeb33/Text-Summarization-Attention-Mechanism |
Decoder Inference: | # decoder inference
#create Input object for hidden and cell state for decoder
#shape of layer with hidden or latent dimension
dec_state_input_h = Input(shape=(latent_dim,))
dec_state_input_c = Input(shape=(latent_dim,))
dec_hidden_state_input = Input(shape=(max_in_len,latent_dim))
# Get the embeddings and input laye... | _____no_output_____ | MIT | text-summarization-attention-mechanism.ipynb | buddhadeb33/Text-Summarization-Attention-Mechanism |
Attention Inference: | #Attention layer
attention = model.layers[8]
attn_out2 = attention([dec_outputs2,dec_hidden_state_input])
merge2 = Concatenate(axis=-1)([dec_outputs2, attn_out2]) | _____no_output_____ | MIT | text-summarization-attention-mechanism.ipynb | buddhadeb33/Text-Summarization-Attention-Mechanism |
Dense layer | #Dense layer
dec_dense = model.layers[10]
dec_outputs2 = dec_dense(merge2)
# Finally define the Model Class
dec_model = Model(
[dec_inputs] + [dec_hidden_state_input,dec_state_input_h,dec_state_input_c],
[dec_outputs2] + [state_h2, state_c2])
#create a dictionary with a key as index and value as words.
reverse_target... | Review : Both the Google platforms provide a great cloud environment for any ML work to be deployed to. The features of them both are equally competent. Notebooks can be downloaded and later uploaded between the two. However, Colab comparatively provides greater flexibility to adjust the batch sizes.Saving or storing o... | MIT | text-summarization-attention-mechanism.ipynb | buddhadeb33/Text-Summarization-Attention-Mechanism |
Brainstorm CTF phantom tutorial datasetHere we compute the evoked from raw for the Brainstorm CTF phantomtutorial dataset. For comparison, see [1]_ and: http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtfReferences----------.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM. Brainstorm: A User-F... | # Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import fit_dipole
from mne.datasets.brainstorm import bst_phantom_ctf
from mne.io import read_raw_ctf
print(__doc__) | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
The data were collected with a CTF system at 2400 Hz. | data_path = bst_phantom_ctf.data_path()
# Switch to these to use the higher-SNR data:
# raw_path = op.join(data_path, 'phantom_200uA_20150709_01.ds')
# dip_freq = 7.
raw_path = op.join(data_path, 'phantom_20uA_20150603_03.ds')
dip_freq = 23.
erm_path = op.join(data_path, 'emptyroom_20150709_01.ds')
raw = read_raw_ctf(... | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
The sinusoidal signal is generated on channel HDAC006, so we can usethat to obtain precise timing. | sinusoid, times = raw[raw.ch_names.index('HDAC006-4408')]
plt.figure()
plt.plot(times[times < 1.], sinusoid.T[times < 1.]) | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
Let's create some events using this signal by thresholding the sinusoid. | events = np.where(np.diff(sinusoid > 0.5) > 0)[1] + raw.first_samp
events = np.vstack((events, np.zeros_like(events), np.ones_like(events))).T | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
The CTF software compensation works reasonably well: | raw.plot() | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
But here we can get slightly better noise suppression, lower localizationbias, and a better dipole goodness of fit with spatio-temporal (tSSS)Maxwell filtering: | raw.apply_gradient_compensation(0) # must un-do software compensation first
mf_kwargs = dict(origin=(0., 0., 0.), st_duration=10.)
raw = mne.preprocessing.maxwell_filter(raw, **mf_kwargs)
raw.plot() | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
Our choice of tmin and tmax should capture exactly one cycle, sowe can make the unusual choice of baselining using the entire epochwhen creating our evoked data. We also then crop to a single time point(@t=0) because this is a peak in our signal. | tmin = -0.5 / dip_freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
baseline=(None, None))
evoked = epochs.average()
evoked.plot()
evoked.crop(0., 0.) | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
Let's use a sphere head geometry model and let's see the coordinatealignement and the sphere location. | sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None)
mne.viz.plot_alignment(raw.info, subject='sample',
meg='helmet', bem=sphere, dig=True,
surfaces=['brain'])
del raw, epochs | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
To do a dipole fit, let's use the covariance provided by the empty roomrecording. | raw_erm = read_raw_ctf(erm_path).apply_gradient_compensation(0)
raw_erm = mne.preprocessing.maxwell_filter(raw_erm, coord_frame='meg',
**mf_kwargs)
cov = mne.compute_raw_covariance(raw_erm)
del raw_erm
dip, residual = fit_dipole(evoked, cov, sphere) | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
Compare the actual position with the estimated one. | expected_pos = np.array([18., 0., 49.])
diff = np.sqrt(np.sum((dip.pos[0] * 1000 - expected_pos) ** 2))
print('Actual pos: %s mm' % np.array_str(expected_pos, precision=1))
print('Estimated pos: %s mm' % np.array_str(dip.pos[0] * 1000, precision=1))
print('Difference: %0.1f mm' % diff)
print('Amplitude: %... | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_phantom_ctf.ipynb | drammock/mne-tools.github.io |
Bracketshttps://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/ | from typing import List
def solution(S) :
stack : List[str] = []
for ch in S :
if ch == '{' or ch == '(' or ch == '[' : stack.append(ch)
else:
if len(stack) == 0 : return 0
lastch = stack.pop()
if ch == '}' and lastch != '{' : return 0
if ch == '... | _____no_output_____ | Apache-2.0 | codility-lessons/7 Stacks and Queues.ipynb | stanislawbartkowski/learnml |
Fishhttps://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/ | from typing import List
def solution(A : List[int], B : List[int]) -> int :
assert(len(A) == len(B))
stackup : List[int] = []
eatenfish : int = 0
for i in range(len(B)) :
if B[i] == 1 : stackup.append(A[i])
else :
while len(stackup) > 0 :
eatenfish += 1
... | _____no_output_____ | Apache-2.0 | codility-lessons/7 Stacks and Queues.ipynb | stanislawbartkowski/learnml |
Nestinghttps://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/ | def solution(S : str) -> int :
numof : int = 0
for c in S :
if c == "(" :
numof += 1
else:
if numof == 0 : return 0
numof -= 1
return 1 if numof == 0 else 0
assert (solution("(()(())())") == 1)
assert (solution("())") == 0)
assert (solution("") ... | _____no_output_____ | Apache-2.0 | codility-lessons/7 Stacks and Queues.ipynb | stanislawbartkowski/learnml |
StoneWallhttps://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ | from typing import List
def solution(H : List[int]) -> int :
assert(len(H) > 0)
stack : List[int] = []
no : int = 0
for i in range(len(H)) :
while (len(stack) > 0) and H[i] < stack[len(stack) -1] :
no += 1
stack.pop()
if len(stack) == 0 or H[i] > stack[len(stack) -1]... | _____no_output_____ | Apache-2.0 | codility-lessons/7 Stacks and Queues.ipynb | stanislawbartkowski/learnml |
Ensemble Learning Initial Imports | import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from pathlib import Path
from collections import Counter
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import confusion_matrix
from imblearn.metrics import classification_report_imbalanced | _____no_output_____ | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
Read the CSV and Perform Basic Data Cleaning | # Load the data
file_path = Path('lending_data.csv')
df = pd.read_csv(file_path)
# Preview the data
df.head()
# homeowner column is categorical, change to numerical so it can be scaled later on
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
label_encoder.fit(df["homeowner"])
df["homeown... | _____no_output_____ | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
Split the Data into Training and Testing | # Create our features
X = df.drop(columns="loan_status")
# Create our target
y = df["loan_status"].to_frame()
X.describe()
# Check the balance of our target values
y['loan_status'].value_counts()
# Split the X and y into X_train, X_test, y_train, y_test
# Create X_train, X_test, y_train, y_test
from sklearn.model_sele... | _____no_output_____ | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
Data Pre-ProcessingScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`). | # Create the StandardScaler instance
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Fit the Standard Scaler with the training data
# When fitting scaling functions, only train on the training dataset
X_scaler = scaler.fit(X_train)
# Scale the training and testing data
X_train_scaled = X_sc... | _____no_output_____ | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
Ensemble LearnersIn this section, you will compare two ensemble algorithms to determine which algorithm results in the best performance. You will train a Balanced Random Forest Classifier and an Easy Ensemble classifier . For each algorithm, be sure to complete the folliowing steps:1. Train the model using the trainin... | # Resample the training data with the BalancedRandomForestClassifier
from imblearn.ensemble import BalancedRandomForestClassifier
brf = BalancedRandomForestClassifier(n_estimators=100, random_state=1) #100 trees
# random forest use 50/50 probability decision, so I think scaled data is not required
brf.fit(X_train, y_t... | _____no_output_____ | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
Easy Ensemble Classifier | # Train the Classifier
from imblearn.ensemble import EasyEnsembleClassifier
eec = EasyEnsembleClassifier(n_estimators=100, random_state=1)
eec.fit(X_train, y_train)
# Calculated the balanced accuracy score
y_pred = eec.predict(X_test)
balanced_accuracy_score(y_test, y_pred)
# Display the confusion matrix
confusion_mat... | pre rec spe f1 geo iba sup
high_risk 0.84 1.00 0.99 0.91 0.99 0.99 625
low_risk 1.00 0.99 1.00 1.00 0.99 0.99 18759
avg / total 0.99 0.99 1.00 0.99 0.99 0... | ADSL | credit_risk_ensemble.ipynb | THaoV1001/Classification-Homework |
pip install pennylane
pip install torch
pip install tensorflow
pip install sklearn
pip install pennylane-qiskit
import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=2)
@qml.qnode(device=dev)
def cos_func(x, w):
qml.RX(x, wires=0)
qml.templates.BasicEntanglerLayers(w, wir... | _____no_output_____ | MIT | Xanadu3.ipynb | olgOk/XanaduTraining | |
Preparing GHZ stateUsing the Autograd interface, train a circuit to prepare the 3-qubit W state:$|W> = {1/sqrt(3)}(001|> + |010> + |100>) | qubits = 3
w = np.array([0, 1, 1, 0, 1, 0, 0, 0]) / np.sqrt(3)
w_projector = w[:, np.newaxis] * w
w_decomp = qml.utils.decompose_hamiltonian(w_projector)
H = qml.Hamiltonian(*w_decomp)
def prepare_w(weights, wires):
qml.templates.StronglyEntanglingLayers(weights, wires=wires)
dev = qml.device("default.qubit", wi... | _____no_output_____ | MIT | Xanadu3.ipynb | olgOk/XanaduTraining |
Quantum-based Optimization | dev = qml.device('default.qubit', wires=1)
@qml.qnode(dev)
def rotation(thetas):
qml.RX(1, wires=0)
qml.RZ(1, wires=0)
qml.RX(thetas[0], wires=0)
qml.RY(thetas[1], wires=0)
return qml.expval(qml.PauliZ(0))
opt = qml.RotoselectOptimizer()
import sklearn.datasets
data = sklearn.datasets.loa... | _____no_output_____ | MIT | Xanadu3.ipynb | olgOk/XanaduTraining |
Parte 1 - Imagens coloridas**TIAGO PEREIRA DALL'OCA - 206341** | from scipy import misc
from scipy import ndimage
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('imagens/baboon.png')
img.shape | _____no_output_____ | MIT | parte1.ipynb | tiagodalloca/mc920-trabalho1 |
a)Aqui é bem autoexplicativo. É criado uma matriz que irá multiplicar os vetores que representam os três canais de cores de cada pixel. | matriz_a = np.array([[0.393, 0.769, 0.189],
[0.394, 0.686, 0.168],
[0.272, 0.534, 0.131]])
img_a = np.dot(img, matriz_a)/255
img_a = img_a.clip(max=[1,1,1])
img_a.shape
plt.imshow(img_a) | _____no_output_____ | MIT | parte1.ipynb | tiagodalloca/mc920-trabalho1 |
b)Semelhante ao item "a", porém agora faremos uma multiplicação vetorial que nos resultará em uma imagem de canal único (imagem cinza). | vetor_b = np.array([0.2989, 0.5870, 0.1140])
img_b = np.tensordot(img, vetor_b, axes=([2], [0]))/255
img_b = img_b.clip(max=[1]).reshape(img.shape[0:2])
img_b.shape
plt.imshow(img_b) | _____no_output_____ | MIT | parte1.ipynb | tiagodalloca/mc920-trabalho1 |
Regular ExpressionsRegular expressions are text-matching patterns described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, from finding repetition, to text-matching, and much more. As you advance in Pyt... | import re
# List of patterns to search for
patterns = ['term1', 'term2']
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
for pattern in patterns:
print('Searching for "%s" in:\n "%s"\n' %(pattern,text))
#Check for match
if re.search(pattern,text):
p... | Searching for "term1" in:
"This is a string with term1, but it does not have the other term."
Match was found.
Searching for "term2" in:
"This is a string with term1, but it does not have the other term."
No Match was found.
| MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Now we've seen that re.search() will take the pattern, scan the text, and then return a **Match** object. If no pattern is found, **None** is returned. To give a clearer picture of this match object, check out the cell below: | # List of patterns to search for
pattern = 'term1'
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
match = re.search(pattern,text)
type(match) | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
This **Match** object returned by the search() method is more than just a Boolean or None, it contains information about the match, including the original input string, the regular expression that was used, and the location of the match. Let's see the methods we can use on the match object: | # Show start of match
match.start()
# Show end
match.end() | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Split with regular expressionsLet's see how we can split with the re syntax. This should look similar to how you used the split() method with strings. | # Term to split on
split_term = '@'
phrase = 'What is the domain name of someone with the email: hello@gmail.com'
# Split the phrase
re.split(split_term,phrase) | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Note how re.split() returns a list with the term to split on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand! Finding all instances of a patternYou can use re.findall() to find all the instances of a pattern in a string. F... | # Returns a list of all matches
re.findall('match','test phrase match is in middle') | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
re Pattern SyntaxThis will be the bulk of this lecture on using re with Python. Regular expressions support a huge variety of patterns beyond just simply finding where a single string occurred. We can use *metacharacters* along with re to find specific types of patterns. Since we will be testing multiple re syntax for... | def multi_re_find(patterns,phrase):
'''
Takes in a list of regex patterns
Prints a list of all matches
'''
for pattern in patterns:
print('Searching the phrase using the re check: %r' %(pattern))
print(re.findall(pattern,phrase))
print('\n') | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Repetition SyntaxThere are five ways to express repetition in a pattern: 1. A pattern followed by the meta-character * is repeated zero or more times. 2. Replace the * with + and the pattern must appear at least once. 3. Using ? means the pattern appears zero or one time. 4. For a specific number of occurre... | test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'
test_patterns = [ 'sd*', # s followed by zero or more d's
'sd+', # s followed by one or more d's
'sd?', # s followed by zero or one d's
'sd{3}', # s followed by three d's
... | Searching the phrase using the re check: 'sd*'
['sd', 'sd', 's', 's', 'sddd', 'sddd', 'sddd', 'sd', 's', 's', 's', 's', 's', 's', 'sdddd']
Searching the phrase using the re check: 'sd+'
['sd', 'sd', 'sddd', 'sddd', 'sddd', 'sd', 'sdddd']
Searching the phrase using the re check: 'sd?'
['sd', 'sd', 's', 's', 'sd', 's... | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Character SetsCharacter sets are used when you wish to match any one of a group of characters at a point in the input. Brackets are used to construct character set inputs. For example: the input [ab] searches for occurrences of either **a** or **b**.Let's see some examples: | test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'
test_patterns = ['[sd]', # either s or d
's[sd]+'] # s followed by one or more s or d
multi_re_find(test_patterns,test_phrase) | Searching the phrase using the re check: '[sd]'
['s', 'd', 's', 'd', 's', 's', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 'd', 's', 'd', 's', 'd', 's', 's', 's', 's', 's', 's', 'd', 'd', 'd', 'd']
Searching the phrase using the re check: 's[sd]+'
['sdsd', 'sssddd', 'sdddsddd', 'sds', 'sssss', 'sdddd'... | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
It makes sense that the first input [sd] returns every instance of s or d. Also, the second input s[sd]+ returns any full strings that begin with an s and continue with s or d characters until another character is reached. ExclusionWe can use ^ to exclude terms by incorporating it into the bracket syntax notation. For... | test_phrase = 'This is a string! But it has punctuation. How can we remove it?' | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Use [^!.? ] to check for matches that are not a !,.,?, or space. Add a + to check that the match appears at least once. This basically translates into finding the words. | re.findall('[^!.? ]+',test_phrase) | _____no_output_____ | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Character RangesAs character sets grow larger, typing every character that should (or should not) match could become very tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point. The format used is [start-end].Comm... |
test_phrase = 'This is an example sentence. Lets see if we can find some letters.'
test_patterns=['[a-z]+', # sequences of lower case letters
'[A-Z]+', # sequences of upper case letters
'[a-zA-Z]+', # sequences of lower or upper case letters
'[A-Z][a-z]+'] # on... | Searching the phrase using the re check: '[a-z]+'
['his', 'is', 'an', 'example', 'sentence', 'ets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters']
Searching the phrase using the re check: '[A-Z]+'
['T', 'L']
Searching the phrase using the re check: '[a-zA-Z]+'
['This', 'is', 'an', 'example', 'sentence', 'Lets... | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
Escape CodesYou can use special escape codes to find specific types of patterns in your data, such as digits, non-digits, whitespace, and more. For example:CodeMeaning\da digit\Da non-digit\swhitespace (tab, space, newline, etc.)\Snon-whitespace\walphanumeric\Wnon-alphanumericEscapes are indicated by prefixing the cha... | test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag'
test_patterns=[ r'\d+', # sequence of digits
r'\D+', # sequence of non-digits
r'\s+', # sequence of whitespace
r'\S+', # sequence of non-whitespace
r'\w+', # alphanumeric charac... | Searching the phrase using the re check: '\\d+'
['1233']
Searching the phrase using the re check: '\\D+'
['This is a string with some numbers ', ' and a symbol #hashtag']
Searching the phrase using the re check: '\\s+'
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
Searching the phrase using the re check... | MIT | Python-Programming/Python-3-Bootcamp/13-Advanced Python Modules/.ipynb_checkpoints/05-Regular Expressions - re-checkpoint.ipynb | vivekparasharr/Learn-Programming |
PTN TemplateThis notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get started ... | %load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
from steves_utils.lazy_iterable_wr... | _____no_output_____ | MIT | experiments/tuned_1v2/oracle.run2/trials/4/trial.ipynb | stevester94/csc500-notebooks |
Required ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean | required_parameters = {
"experiment_name",
"lr",
"device",
"seed",
"dataset_seed",
"labels_source",
"labels_target",
"domains_source",
"domains_target",
"num_examples_per_domain_per_label_source",
"num_examples_per_domain_per_label_target",
"n_shot",
"n_way",
"n_q... | _____no_output_____ | MIT | experiments/tuned_1v2/oracle.run2/trials/4/trial.ipynb | stevester94/csc500-notebooks |
Recommender Systems 2018/19 Practice 4 - Similarity with Cython Cython is a superset of Python, allowing you to use C-like operations and import C code. Cython files (.pyx) are compiled and support static typing. | import time
import numpy as np | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Let's implement something simple | def isPrime(n):
i = 2
# Usually you loop up to sqrt(n)
while i < n:
if n % i == 0:
return False
i += 1
return True
print("Is prime 2? {}".format(isPrime(2)))
print("Is prime 3? {}".format(isPrime(3)))
print("Is prime 5? {}".format(isPrime(5)))
prin... | Is Prime 80000023? True, time required 8.19 sec
| MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Load Cython magic command, this takes care of the compilation step. If you are writing code outside Jupyter you'll have to compile using other tools | %load_ext Cython | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Declare Cython function, paste the same code as before. The function will be compiled and then executed with a Python interface | %%cython
def isPrime(n):
i = 2
# Usually you loop up to sqrt(n)
while i < n:
if n % i == 0:
return False
i += 1
return True
start_time = time.time()
result = isPrime(80000023)
print("Is Prime 80000023? {}, time required {:.2f} sec".format(result,... | Is Prime 80000023? True, time required 4.81 sec
| MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
As you can see by just compiling the same code we got some improvement. To go seriously higher, we have to use some static tiping | %%cython
# Declare the tipe of the arguments
def isPrime(long n):
# Declare index of for loop
cdef long i
i = 2
# Usually you loop up to sqrt(n)
while i < n:
if n % i == 0:
return False
i += 1
return True
start_time = time.time()
resu... | Is Prime 80000023? True, time required 0.94 sec
| MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Cython code with two tipe declaration, for n and i, runs 50x faster than Python Main benefits of Cython:* Compiled, no interpreter* Static typing, no overhead* Fast loops, no need to vectorize. Vectorization sometimes performes lots of useless operations* Numpy, which is fast in python, becomes often slooooow compare... | from urllib.request import urlretrieve
import zipfile
# skip the download
#urlretrieve ("http://files.grouplens.org/datasets/movielens/ml-10m.zip", "data/Movielens_10M/movielens_10m.zip")
dataFile = zipfile.ZipFile("data/Movielens_10M/movielens_10m.zip")
URM_path = dataFile.extract("ml-10M100K/ratings.dat", path = "da... | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Since we cannot store in memory the whole similarity, we compute it one row at a time | itemIndex=1
item_ratings = URM_train[:,itemIndex]
item_ratings = item_ratings.toarray().squeeze()
item_ratings.shape
this_item_weights = URM_train.T.dot(item_ratings)
this_item_weights.shape | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Once we have the scores for that row, we get the TopK | k=10
top_k_idx = np.argsort(this_item_weights) [-k:]
top_k_idx
import scipy.sparse as sps
# Function hiding some conversion checks
def check_matrix(X, format='csc', dtype=np.float32):
if format == 'csc' and not isinstance(X, sps.csc_matrix):
return X.tocsc().astype(dtype)
elif format == 'csr' and not i... | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Create a Basic Collaborative filtering recommender using only cosine similarity | class BasicItemKNN_CF_Recommender(object):
""" ItemKNN recommender with cosine similarity and no shrinkage"""
def __init__(self, URM):
self.dataset = URM
def compute_similarity(self, URM):
# We explore the matrix column-wise
URM = check_matrix(URM, 'csc') ... | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Let's isolate the compute_similarity function | def compute_similarity(URM, k=100):
# We explore the matrix column-wise
URM = check_matrix(URM, 'csc')
n_items = URM.shape[0]
values = []
rows = []
cols = []
start_time = time.time()
processedItems = 0
# Compute all similarities for each item using vectorization
# for it... | Similarity item 100, 81.61 item/sec, required time 14.62 min
Similarity item 200, 80.34 item/sec, required time 14.85 min
Similarity item 300, 80.08 item/sec, required time 14.89 min
Similarity item 400, 80.50 item/sec, required time 14.82 min
Similarity item 500, 80.02 item/sec, required time 14.91 min
Similarity item... | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
We see that computing the similarity takes more or less 15 minutes Now we use the same identical code, but we compile it | %%cython
import time
import numpy as np
import scipy.sparse as sps
def compute_similarity_compiled(URM, k=100):
# We explore the matrix column-wise
URM = URM.tocsc()
n_items = URM.shape[0]
values = []
rows = []
cols = []
start_time = time.time()
processedItems = 0
# Compute... | Similarity item 100, 56.48 item/sec, required time 21.12 min
Similarity item 200, 56.12 item/sec, required time 21.25 min
Similarity item 300, 56.58 item/sec, required time 21.08 min
Similarity item 400, 56.42 item/sec, required time 21.14 min
Similarity item 500, 56.74 item/sec, required time 21.02 min
Similarity item... | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
As opposed to the previous example, compilation by itself is not very helpful. Why? Because the compiler is just porting in C all operations that the python interpreter would have to perform, dynamic tiping included Now try to add some tipes | %%cython
import time
import numpy as np
import scipy.sparse as sps
cimport numpy as np
def compute_similarity_compiled(URM, int k=100):
cdef int itemIndex, processedItems
# We use the numpy syntax, allowing us to perform vectorized operations
cdef np.ndarray[double, ndim=1] item_ratings, this_it... | Similarity item 100, 57.80 item/sec, required time 20.64 min
Similarity item 200, 53.69 item/sec, required time 22.22 min
Similarity item 300, 54.57 item/sec, required time 21.86 min
Similarity item 400, 54.07 item/sec, required time 22.06 min
Similarity item 500, 54.65 item/sec, required time 21.83 min
Similarity item... | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Still no luck! Why? There are a few reasons:* We are getting the data from the sparse matrix using its interface, which is SLOW* We are transforming sparse data into a dense array, which is SLOW* We are performing a dot product against a dense vector You colud find a workaround... here we do something different Propo... | data_matrix = np.array([[1,1,0,1],[0,1,1,1],[1,0,1,0]])
data_matrix = sps.csc_matrix(data_matrix)
data_matrix.todense() | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Example: Compute the similarities for item 1 Step 1: get users that rated item 1 | users_rated_item = data_matrix[:,1]
users_rated_item.indices | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Step 2: count how many times those users rated other items | item_similarity = data_matrix[users_rated_item.indices].sum(axis = 0)
np.array(item_similarity).squeeze() | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Verify our result against the common method. We can see that the similarity values for col 1 are identical | similarity_matrix_product = data_matrix.T.dot(data_matrix)
similarity_matrix_product.toarray()[:,1]
# The following code works for implicit feedback only
def compute_similarity_new_algorithm(URM, k=100):
# We explore the matrix column-wise
URM = check_matrix(URM, 'csc')
URM.data = np.ones_like(URM.data)
... | Similarity item 100, 28.04 item/sec, required time 42.53 min
Similarity item 200, 28.37 item/sec, required time 42.04 min
Similarity item 300, 28.85 item/sec, required time 41.35 min
Similarity item 400, 28.77 item/sec, required time 41.45 min
Similarity item 500, 29.20 item/sec, required time 40.85 min
Similarity item... | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Slower but expected, dot product operations are implemented in an efficient way and here we are using an indirect approach Now let's write this algorithm in Cython | %%cython
import time
import numpy as np
cimport numpy as np
from cpython.array cimport array, clone
import scipy.sparse as sps
cdef class Cosine_Similarity:
cdef int TopK
cdef long n_items
# Arrays containing the sparse data
cdef int[:] user_to_item_row_ptr, user_to_item_cols
cdef int[:] item... | Similarity item 10000 ( 15 % ), 722.73 item/sec, required time 1.27 min
Similarity item 20000 ( 31 % ), 1152.12 item/sec, required time 0.65 min
Similarity item 30000 ( 46 % ), 1413.59 item/sec, required time 0.41 min
Similarity item 40000 ( 61 % ), 1611.02 item/sec, required time 0.26 min
Similarity item 50000 ( 77 % ... | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Better... much better. There are a few other things you could do, but at this point it is not worth the effort How to use Cython outside a notebook Step1: Create a .pyx file and write your code Step2: Create a compilation script "compileCython.py" with the following content | # This code will not run in a notebook cell
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import sys
import re
if len(sys.argv) != ... | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
Step3: Compile your code with the following command python compileCython.py Cosine_Similarity_Cython.pyx build_ext --inplace Step4: Generate cython report and look for "yellow lines". The report is an .html file which represents how many operations are necessary to translate each python operation in cython code. If a... | from Base.Simialrity.Cython.Cosine_Similarity_Cython import Cosine_Similarity
cosine_cython = Cosine_Similarity(URM_train, TopK=100)
start_time = time.time()
cosine_cython.compute_similarity()
print("Similarity computed in {:.2f} seconds".format(time.time()-start_time)) | _____no_output_____ | MIT | Jupyter notebook/Practice 4 - Cython.ipynb | marcomussi/RecommenderSystemPolimi |
15 PDEs: Solution with Time Stepping Heat EquationThe **heat equation** can be derived from Fourier's law and energy conservation (see the [lecture notes on the heat equation (PDF)](https://github.com/ASU-CompMethodsPhysics-PHY494/PHY494-resources/blob/master/15_PDEs/15_PDEs_LectureNotes_HeatEquation.pdf))$$\frac{\par... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
def T_bar(x, t, T0, L, K=237, C=900, rho=2700, nmax=1000):
T = np.zeros_like(x)
eta = K / (C*rho)
for n in range(1, nmax, 2):
kn = n*np.pi/L
T += 4*T0/(np.pi * n) * np.sin(kn*x) * np.exp(-kn*kn * et... | _____no_output_____ | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
Numerical solution: Leap frogDiscretize (finite difference):For the time domain we only have the initial values so we use a simple forward difference for the time derivative:$$\frac{\partial T(x,t)}{\partial t} \approx \frac{T(x, t+\Delta t) - T(x, t)}{\Delta t}$$ For the spatial derivative we have initially all value... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook | _____no_output_____ | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
For HTML/nbviewer output, use inline: | %matplotlib inline
L_rod = 1. # m
t_max = 3000. # s
Dx = 0.02 # m
Dt = 2 # s
Nx = int(L_rod // Dx)
Nt = int(t_max // Dt)
Kappa = 237 # W/(m K)
CHeat = 900 # J/K
rho = 2700 # kg/m^3
T0 = 373 # K
Tb = 273 # K
eta = Kappa * Dt / (CHeat * rho * Dx**2)
eta2 = 1 - 2*eta
step = 20 # plot solution every n steps... | Nx = 49, Nt = 1500
eta = 0.4876543209876543
Iteration 20
Iteration 40
Iteration 60
Iteration 80
Iteration 100
Iteration 120
Iteration 140
Iteration 160
Iteration 180
Iteration 200
Iteration 220
Iteration 240
Iteration 260
Iteration 280
Iteration 300
Iteration 320
Iteration 340
Iter... | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
VisualizationVisualize (you can use the code as is). Note how we are making the plot use proper units by mutiplying with `Dt * step` and `Dx`. | X, Y = np.meshgrid(range(T_plot.shape[0]), range(T_plot.shape[1]))
Z = T_plot[X, Y]
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot_wireframe(X*Dt*step, Y*Dx, Z)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"position $x$ (m)")
ax.set_zlabel(r"temperature $T$ (K)")
fig.tight_layout() | _____no_output_____ | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
2D as above for the analytical solution… | X = Dx * np.arange(T_plot.shape[1])
plt.plot(X, T_plot.T)
plt.xlabel(r"$x$ (m)")
plt.ylabel(r"$T$ (K)"); | _____no_output_____ | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
Slower solution I benchmarked this slow solution at 89.7 ms and the fast solution at 14.8 ms (commented out all `print`) so the explicit loop is not that much worse (probably because the overhead on array copying etc is high). | L_rod = 1. # m
t_max = 3000. # s
Dx = 0.02 # m
Dt = 2 # s
Nx = int(L_rod // Dx)
Nt = int(t_max // Dt)
Kappa = 237 # W/(m K)
CHeat = 900 # J/K
rho = 2700 # kg/m^3
T0 = 373 # K
Tb = 273 # K
eta = Kappa * Dt / (CHeat * rho * Dx**2)
eta2 = 1 - 2*eta
step = 20 # plot solution every n steps
print("Nx = {0}, ... | _____no_output_____ | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
Stability of the solution Empirical investigation of the stabilityInvestigate the solution for different values of `Dt` and `Dx`. Can you discern patters for stable/unstable solutions?Report `Dt`, `Dx`, and `eta`* for 3 stable solutions * for 3 unstable solutions | def calculate_T(L_rod=1, t_max=3000, Dx=0.02, Dt=2, T0=373, Tb=273,
step=20):
Nx = int(L_rod // Dx)
Nt = int(t_max // Dt)
Kappa = 237 # W/(m K)
CHeat = 900 # J/K
rho = 2700 # kg/m^3
eta = Kappa * Dt / (CHeat * rho * Dx**2)
eta2 = 1 - 2*eta
print("Nx = {0}, Nt = {1}".fo... | Nx = 99, Nt = 1500
eta = 1.9506172839506173
Iteration 20
Iteration 40
Iteration 60
Iteration 80
Iteration 100
Iteration 120
Iteration 140
Iteration 160
Iteration 180
Iteration 200
Iteration 220
Iteration 240
Iteration 260
Iteration 280
Iteration 300
Iteration 320
Iteration 340
Iter... | CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
Note that *decreasing* the value of $\Delta x$ made the solution *unstable*. This is strange, we have gotten used to the idea that working on a finer mesh will increase the detail (until we hit round-off error) and just become computationally more expensive. But here the algorithm suddenly becomes unstable (and it is n... | Dt = 2
Dx = 0.02
eta = Kappa * Dt /(CHeat * rho * Dx*Dx)
print(eta) | 0.4876543209876543
| CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
... and this was unstable, despite a seemingly small change: | Dt = 2
Dx = 0.01
eta = Kappa * Dt /(CHeat * rho * Dx*Dx)
print(eta) | 1.9506172839506173
| CC-BY-4.0 | 15_PDEs/15_PDEs.ipynb | ASU-CompMethodsPhysics-PHY494/PHY494-resources-2018 |
Build a sklearn Pipeline for a to ML contest submissionIn the ML_coruse_train notebook we at first analyzed the housing dataset to gain statistical insights and then e.g. features added new, replaced missing values and scaled the colums using pandas dataset methods.In the following we will use sklearn [Pipelines](http... | # read housing data again
import pandas as pd
import numpy as np
housing = pd.read_csv("datasets/housing/housing.csv")
# Try to get header information of the dataframe:
housing.head() | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
One remark: sklearn transformers do **not** act on pandas dataframes. Instead, they use numpy arrays. Now try to [convert](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html) a dataframe to a numpy array: | housing.head().to_numpy() | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
As you can see, the column names are lost now.In a numpy array, columns indexed using integers and no more by their names. Add extra feature columnsAt first, we again add some extra columns (e.g. `rooms_per_household, population_per_household, bedrooms_per_household`) which might correlate better with the predicted p... | from sklearn.preprocessing import FunctionTransformer
# At first, get the indexes as integers from the column names:
rooms_ix = housing.columns.get_loc("total_rooms")
bedrooms_ix =
population_ix =
household_ix =
# Now implement a function which takes a numpy array a argument and adds the new feature columns
def ad... | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Imputing missing elementsFor replacing nan values in the dataset with the mean or median of the column they are in, you can also use a [SimpleImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html) : | from sklearn.impute import SimpleImputer
# Drop the categorial column ocean_proximity
housing_num = housing.drop(...)
print("We have %d nan elements in the numerical columns" %np.count_nonzero(np.isnan(housing_num.to_numpy())))
imp_mean = ...
housing_num_cleaned = imp_mean.fit_transform(housing_num)
assert np.coun... | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Column scalingFor scaling and normalizing the columns, you can use the class [StandardScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)Use numpy [mean](https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html) and [std](https://docs.scipy.org/doc/numpy/ref... | from sklearn.preprocessing import StandardScaler
scaler = ...
scaled = scaler.fit_transform(housing_num_cleaned)
print("mean of the columns is: " , ...)
print("standard deviation of the columns is: " , ...) | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Putting all preprocessing steps together Now let's build a pipeline for preprocessing the **numerical** attributes.The pipeline shall process the data in the following steps:* [Impute](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html) median or mean values for elements which are NaN... | from sklearn.pipeline import Pipeline
num_pipeline = Pipeline([
('give a name', ...), # Imputer
('give a name', ...), # FunctionTransformer
('give a name', ...), # Scaler
])
# Now test the pipeline on housing_num
num_pipeline.fit_transform(housing_num) | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Now we have a pipeline for the numerical columns. But we still have a categorical column: | housing['ocean_proximity'].head() | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
We need one more pipeline for the categorical column. Instead of the "Dummy encoding" we used before, we now use the [OneHotEncoder](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html) from sklearn. Hint: to make things easier, set the sparse option of the OneHotEncoder to False... | from sklearn.preprocessing import OneHotEncoder
housing_cat = housing[] #get the right column
cat_encoder =
housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
housing_cat_1hot | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
We have everything we need for building a preprocessing pipeline which transforms the columns including all the steps before. Since we have columns where different transformations should be applied, we use the class [ColumnTransformer](https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer... | from sklearn.compose import ColumnTransformer
# These are the columns with the numerical features:
num_attribs = ["longitude", ...]
# Here are the columns with categorical features:
cat_attribs = [...]
full_prep_pipeline = ColumnTransformer([
("give a name", ..., ...), # Add the numerical pipeline and specif... | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Train an estimatorInclude `full_prep_pipeline` into a further pipeline where it is followed by an RandomForestRegressor. This way, at first our data is prepared using `full_prep_pipeline` and then the RandomForestRegressor is trained on it. | from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
full_pipeline_with_predictor = Pipeline([
("give a name", full_prep_pipeline), # add the full_prep_pipeline
("give a name", RandomForestRegressor()) # Add a RandomForestRegressor
]) | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
For training the regressor, seperate the label colum (`median_house_value`) and feature columns (all other columns).Split the data into a training and testing dataset using train_test_split. | # Create two dataframes, one for the labels one for the features
housing_features = housing...
housing_labels = housing
# Split the two dataframes into a training and a test dataset
X_train, X_test, y_train, y_test = train_test_split(housing_features, housing_labels, test_size = 0.20)
# Now train the full_pipeline_wi... | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
As usual, calculate some score metrics: | from sklearn.metrics import mean_squared_error
y_pred = full_pipeline_with_predictor.predict(X_test)
tree_mse = mean_squared_error(y_pred, y_test)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
from sklearn.metrics import r2_score
r2_score(y_pred, y_test) | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Use the [pickle serializer](https://docs.python.org/3/library/pickle.html) to save your estimator to a file for contest participation. | import pickle
import getpass
from sklearn.utils.validation import check_is_fitted
your_regressor = ... # Put your regression pipeline here
assert isinstance(your_regressor, Pipeline)
pickle.dump(your_regressor, open(getpass.getuser() + "s_model.p", "wb" ) ) | _____no_output_____ | Apache-2.0 | ML_course/ML_Contest_train.ipynb | Riwedieb/handson-ml |
Running the Direct Fidelity Estimation (DFE) algorithmThis example walks through the steps of running the direct fidelity estimation (DFE) algorithm as described in these two papers:* Direct Fidelity Estimation from Few Pauli Measurements (https://arxiv.org/abs/1104.4695)* Practical characterization of quantum devices... | try:
import cirq
except ImportError:
print("installing cirq...")
!pip install --quiet cirq
print("installed cirq.")
# Import Cirq, DFE, and create a circuit
import cirq
from cirq.contrib.svg import SVGCircuit
import examples.direct_fidelity_estimation as dfe
qubits = cirq.LineQubit.range(3)
circuit = c... | _____no_output_____ | Apache-2.0 | examples/direct_fidelity_estimation.ipynb | mganahl/Cirq |
What is happening under the hood?Now, let's look at the `intermediate_results` and correlate what is happening in the code with the papers. The definition of fidelity is:$$F = F(\hat{\rho},\hat{\sigma}) = \mathrm{Tr} \left(\hat{\rho} \hat{\sigma}\right)$$where $\hat{\rho}$ is the theoretical pure state and $\hat{\sigm... | for pauli_trace in intermediate_results.pauli_traces:
print('Probability %.3f\tPauli: %s' % (pauli_trace.Pr_i, pauli_trace.P_i)) | _____no_output_____ | Apache-2.0 | examples/direct_fidelity_estimation.ipynb | mganahl/Cirq |
Yay! We do see 8 entries (we have 3 qubits) with all the same 1/8 probability. What if we had a 23 qubit circuit? In this case, that would be quite many of them. That is where the parameter `n_measured_operators` becomes useful. If it is set to `None` we return *all* the Pauli strings (regardless of whether the circuit... | for trial_result in intermediate_results.trial_results:
print('rho_i=%.3f\tsigma_i=%.3f\tPauli:%s' % (trial_result.pauli_trace.rho_i, trial_result.sigma_i, trial_result.pauli_trace.P_i)) | _____no_output_____ | Apache-2.0 | examples/direct_fidelity_estimation.ipynb | mganahl/Cirq |
Gujarati with CLTK See how you can analyse your Gujarati texts with CLTK ! Let's begin by adding the `USER_PATH`.. | import os
USER_PATH = os.path.expanduser('~') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
In order to be able to download Gujarati texts from CLTK's Github repo, we will require an importer. | from cltk.corpus.utils.importer import CorpusImporter
gujarati_downloader = CorpusImporter('gujarati') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
We can now see the corpora available for download, by using `list_corpora` feature of the importer. Let's go ahead and try it out! | gujarati_downloader.list_corpora | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
The corpus gujarati_text_wikisource can be downloaded from the Github repo. The corpus will be downloaded to the directory `cltk_data/gujarati` at the above mentioned `USER_PATH` | gujarati_downloader.import_corpus('gujarati_text_wikisource') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
You can see the texts downloaded by doing the following, or checking out the `cltk_data/gujarati/text/gujarati_text_wikisource` directory. | gujarati_corpus_path = os.path.join(USER_PATH,'cltk_data/gujarati/text/gujarati_text_wikisource')
list_of_texts = [text for text in os.listdir(gujarati_corpus_path) if '.' not in text]
print(list_of_texts) | ['narsinh_mehta', 'kabir', 'vallabhacharya']
| MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Great, now that we have our texts, let's take a sample from one of them. For this tutorial, we shall be using govinda_khele_holi , a text by the Gujarati poet Narsinh Mehta. | gujarati_text_path = os.path.join(gujarati_corpus_path,'narsinh_mehta/govinda_khele_holi.txt')
gujarati_text = open(gujarati_text_path,'r').read()
print(gujarati_text) | વૃંદાવન જઈએ,
જીહાં ગોવિંદ ખેલે હોળી;
નટવર વેશ ધર્યો નંદ નંદન,
મળી મહાવન ટોળી... ચાલો સખી !
એક નાચે એક ચંગ વજાડે,
છાંટે કેસર ઘોળી;
એક અબીરગુલાલ ઉડાડે,
એક ગાય ભાંભર ભોળી... ચાલો સખી !
એક એકને કરે છમકલાં,
હસી હસી કર લે તાળી;
માહોમાહે કરે મરકલાં,
મધ્ય ખેલે વનમાળી... ચાલો સખી !
વસંત ઋતુ વૃંદાવન સરી,
ફૂલ્યો ફાગણ માસ;
ગોવ... | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Gujarati Alphabets There are 13 vowels, 33 consonants, which are grouped as follows: | from cltk.corpus.gujarati.alphabet import *
print("Digits:",DIGITS)
print("Vowels:",VOWELS)
print("Dependent vowels:",DEPENDENT_VOWELS)
print("Consonants:",CONSONANTS)
print("Velar consonants:",VELAR_CONSONANTS)
print("Palatal consonants:",PALATAL_CONSONANTS)
print("Retroflex consonants:",RETROFLEX_CONSONANTS)
print("D... | Digits: ['૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', '૯', '૧૦']
Vowels: ['અ', 'આ', 'ઇ', 'ઈ', 'ઉ', 'ઊ', 'ઋ', 'એ', 'ઐ', 'ઓ', 'ઔ', 'અં', 'અઃ']
Dependent vowels: ['ા ', 'િ', 'ી', 'ો', 'ૌ']
Consonants: ['ક', 'ખ', 'ગ', 'ઘ', 'ચ', 'છ', 'જ', 'ઝ', 'ઞ', 'ટ', 'ઠ', 'ડ', 'ઢ', 'ણ', 'ત', 'થ', 'દ', 'ધ', 'ન', 'પ', 'ફ', 'બ', 'ભ', 'મ', '... | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Transliterations We can transliterate Gujarati scripts to that of other Indic languages. Let us transliterate `કમળ ભારતનો રાષ્ટ્રીય ફૂલ છે`to Kannada: | gujarati_text_two = 'કમળ ભારતનો રાષ્ટ્રીય ફૂલ છે'
from cltk.corpus.sanskrit.itrans.unicode_transliterate import UnicodeIndicTransliterator
UnicodeIndicTransliterator.transliterate(gujarati_text_two,"gu","kn") | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
We can also romanize the text as shown: | from cltk.corpus.sanskrit.itrans.unicode_transliterate import ItransTransliterator
ItransTransliterator.to_itrans(gujarati_text_two,'gu') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Similarly, we can indicize a text given in its ITRANS-transliteration | gujarati_text_itrans = 'bhaawanaa'
ItransTransliterator.from_itrans(gujarati_text_itrans,'gu') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Syllabifier We can use the indian_syllabifier to syllabify the Gujarati sentences. To do this, we will have to import models as follows. The importing of `sanskrit_models_cltk` might take some time. | phonetics_model_importer = CorpusImporter('sanskrit')
phonetics_model_importer.list_corpora
phonetics_model_importer.import_corpus('sanskrit_models_cltk') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Now we import the syllabifier and syllabify as follows: | %%capture
from cltk.stem.sanskrit.indian_syllabifier import Syllabifier
gujarati_syllabifier = Syllabifier('gujarati')
gujarati_syllables = gujarati_syllabifier.orthographic_syllabify('ભાવના') | _____no_output_____ | MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.