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 |
|---|---|---|---|---|---|
K-means algorithmThis function finds the centers and variances given uncategorized inputs and number of clusters. It also takes in a flag to determined whether to output an averaged variance for all clusters or use specialized variances for each cluster.The algorithm begins by choosing random points from the inputs as... | def kmeans(clusters=2, X=X, use_same_width=False):
centers = np.random.choice(X, clusters, replace=False)
diff = 1
while diff != 0:
assigned = [[] for i in range(clusters)]
for x in X:
assigned_center = np.argmin(np.abs(centers - x))
assigned[assigned_center].append(x.item())
new_centers =... | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
The function below defines the gaussian function. Given the centers and variances for all clusters, it calculates the output for all gaussians at once for a single input. | def gaussian(centers, variances, x):
return np.exp((-1 / (2 * variances)) * ((centers - x) ** 2)) | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
Training the RBF NetworkFor each gaussian, a random weight is generated in the interval [-1, 1]. The same happens for a bias term as well.Then, for the number of epochs specified, the algorithm calculates the gaussian outputs for each input, and then takes the weighted sum and adds the bias to get the output of the ne... | def train(centers, variances, lr, epochs=100):
num_centers = len(centers)
W = np.random.rand(1, num_centers) * 2 - 1
b = np.random.rand(1, 1) * 2 - 1
order = list(range(len(X)))
for i in range(epochs):
random.shuffle(order)
for j in order:
x = X[j]
d = D[j]
G = gaussian(centers, vari... | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
The learning rates and number of bases that needed to be tested are defined, and then K-means is run for each combination of base and learning rate. The output of the K-means is used as the input for the RBF training algorithm, and the results are plotted. | bases = [2, 4, 7, 11, 16]
learning_rates = [.01, .02]
for base in bases:
for lr in learning_rates:
centers, variances = kmeans(base, X)
train(centers=centers, variances=variances, lr=lr) | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
The best function approximates seem to be with 2 bases. As soon as the bases are increased to 4, overfitting starts to occur, with 16 bases having extreme overfitting.Increasing the learning rate seems to decrease the training error but in some cases increases the overfitting of the data. Run the same combinations or n... | for base in bases:
for lr in learning_rates:
centers, variances = kmeans(base, X, use_same_width=True)
train(centers=centers, variances=variances, lr=lr, epochs=100) | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
To finish, check out: http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1992AJ....104.2213L&data_type=PDF_HIGH&whole_paper=YES&type=PRINTER&filetype=.pdf | # Third-party
from astropy.io import ascii, fits
import astropy.coordinates as coord
import astropy.units as u
from astropy.constants import c
import matplotlib as mpl
import matplotlib.pyplot as pl
import numpy as np
from scipy.interpolate import interp1d
pl.style.use('apw-notebook')
%matplotlib inline
# pl.style.use... | _____no_output_____ | MIT | notebooks/fit-spectrum.ipynb | adrn/ebak |
---try using levmar to optimize | from scipy.optimize import leastsq
def errfunc(pars, data_spec, ref_spec):
v1,v2,a,b,c = pars
X = get_design_matrix(data_spec, ref_spec, v1*u.km/u.s, v2*u.km/u.s)
synth_spec = make_synthetic_spectrum(X, [a,b,c])
return (synth_spec - data_spec['flux'])
levmar_opt_pars,ier = leastsq(errfunc, x0=[35,-5]+op... | _____no_output_____ | MIT | notebooks/fit-spectrum.ipynb | adrn/ebak |
Final Checks for model | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv(f"D:/Docs/train_1.csv", encoding='mac_roman') | _____no_output_____ | MIT | 4_Applied ML with Python/Course/Week-4/Check_Last_Logreg.ipynb | syedmeesamali/CourseraPlus |
1. Use ONLY compliance available columns | df = df[df['compliance'].notna()]
df.shape
df['fine_amount'] = df['fine_amount'].fillna(0)
df.shape
df['compliance'].value_counts() | _____no_output_____ | MIT | 4_Applied ML with Python/Course/Week-4/Check_Last_Logreg.ipynb | syedmeesamali/CourseraPlus |
2. Build the actual model | from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
feature_names_tickets = ['ticket_id', 'fine_amount']
X_tickets = df[feature_names_tickets]
y_tickets = df['compliance']
#Test size is chosen to get X_test value of 61,001 as the same is provided test data
X_train, ... | (98879, 2)
(61001, 2)
| MIT | 4_Applied ML with Python/Course/Week-4/Check_Last_Logreg.ipynb | syedmeesamali/CourseraPlus |
3. Apply GridSearchCV | from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000] }
grid_search = GridSearchCV(estimator = clf, param_grid = param_grid,
scoring = 'accuracy', cv = 5, verbose=0)
grid_search.fit(X_train, y_train)
print('Best coring:\n Best C: {}'.format(g... | _____no_output_____ | MIT | 4_Applied ML with Python/Course/Week-4/Check_Last_Logreg.ipynb | syedmeesamali/CourseraPlus |
7. Check ROC / AUC | # First we need to load our test dataset
df1 = pd.read_csv(f"D:/Docs/test_1.csv", encoding='mac_roman')
df1['fine_amount'] = df1['fine_amount'].fillna(0)
df1.shape
feature_names_test = ['ticket_id', 'fine_amount']
X_test_new = df1[feature_names_test]
print(X_test.shape)
print(X_test_new.shape)
from sklearn.metrics impo... | _____no_output_____ | MIT | 4_Applied ML with Python/Course/Week-4/Check_Last_Logreg.ipynb | syedmeesamali/CourseraPlus |
Tokenizers BackgroundFor Natural Language Processing, tokenization is an essential part of data preprocessing. It is the process of splitting a string into a list of tokens. One can think of token as parts like a word is a token in a sentence.Depending on the application, different tokenizers are more suitable than ot... | nemo_nlp.modules.get_tokenizer_list() | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Hugging Face AutoTokenizer | # instantiate tokenizer wrapper using pretrained model name only
tokenizer1 = nemo_nlp.modules.get_tokenizer(tokenizer_name="bert-base-cased")
# the wrapper has a reference to the original HuggingFace tokenizer
print(tokenizer1.tokenizer)
# check vocabulary (this can be very long)
print(tokenizer1.tokenizer.vocab)
# s... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Adding Special tokensWe do not recommend overwriting special tokens for Hugging Face pretrained models, since these are the commonly used default values. If a user still wants to overwrite the special tokens, specify some of the following keys: | special_tokens_dict = {"unk_token": "<UNK>",
"sep_token": "<SEP>",
"pad_token": "<PAD>",
"bos_token": "<CLS>",
"mask_token": "<MASK>",
"eos_token": "<SEP>",
"cls_token": "<CLS>"}... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Notice, that if you specify tokens that were not previously included in the tokenizer's vocabulary file, new tokens will be added to the vocabulary file. You will see a message like this: `['', '', '', '', '', '', ''] will be added to the vocabulary. Please resize your model accordingly` | # A safer way to add special tokens is the following:
# define your model
pretrained_model_name = 'bert-base-uncased'
config = {"language_model": {"pretrained_model_name": pretrained_model_name}, "tokenizer": {}}
omega_conf = OmegaConf.create(config)
model = nemo_nlp.modules.get_lm_model(cfg=omega_conf)
# define pret... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
As you can see in the above, the tokenizer splits `` into subtokens. Let's add this to the special tokens to make sure the tokenizer does not split this into subtokens. | special_tokens = {'bos_token': '<BOS>',
'cls_token': '<CSL>',
'additional_special_tokens': ['<MY_NEW_TOKEN>', '<ANOTHER_TOKEN>']}
tokenizer_default.add_special_tokens(special_tokens_dict=special_tokens)
# resize your model so that the embeddings for newly added tokens are updated du... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Now, the model doesn't break down our special token into the subtokens. Megatron model tokenizer | # Megatron tokenizers are instances of the Hugging Face BertTokenizer.
tokenizer4 = nemo_nlp.modules.get_tokenizer(tokenizer_name="megatron-bert-cased") | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Train custom tokenizer model and vocabulary from text file We use the [`scripts/tokenizers/process_asr_text_tokenizer.py`](https://github.com/NVIDIA/NeMo/blob/stable/scripts/tokenizers/process_asr_text_tokenizer.py) script to create a custom tokenizer model with its own vocabulary from an input file | # download tokenizer script
script_file = "process_asr_text_tokenizer.py"
if not os.path.exists(script_file):
print('Downloading script file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/tokenizers/process_asr_text_tokenizer.py')
else:
print ('Script already exists')
#... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Use custom tokenizer for data preprocessing Example: SentencePiece for BPE | # initialize tokenizer with created tokenizer model, which inherently includes the vocabulary and specify optional special tokens
tokenizer_spe = nemo_nlp.modules.get_tokenizer(tokenizer_name="sentencepiece", tokenizer_model=spe_model_dir+"/tokenizer.model", special_tokens=special_tokens_dict)
# specified special toke... | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
Using any tokenizer to tokenize text into BERT compatible input | text="hello world"
# create tokens
tokenized = [tokenizer_spe.bos_token] + tokenizer_spe.text_to_tokens(text) + [tokenizer_spe.eos_token]
print(tokenized)
# turn token into input_ids for a neural model, such as BERTModule
print(tokenizer_spe.tokens_to_ids(tokenized)) | _____no_output_____ | Apache-2.0 | tutorials/nlp/02_NLP_Tokenizers.ipynb | shahin-trunk/NeMo |
T2 Ramsey Experiment This experiment serves as one of the series of experiments used to characterize a single qubit. Its purpose is to determine two of the qubit's properties: *Ramsey* or *detuning frequency* and $T_2\ast$. The rough frequency of the qubit was already determined previously. Here, we would like to meas... | import qiskit
from qiskit_experiments.library import T2Ramsey | _____no_output_____ | Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
The circuit used for the experiment comprises the following: 1. Hadamard gate 2. delay 3. p (phase) gate that rotates the qubit in the x-y plane 4. Hadamard gate 5. measurementDuring the delay time, we expect the qubit to precess about the z-axis. If the p gate and the precession offset each other perfe... | # set the computation units to microseconds
unit = 'us' #microseconds
qubit = 0
# set the desired delays
delays = list(range(1, 150, 2))
# Create a T2Ramsey experiment. Print the first circuit as an example
exp1 = T2Ramsey(qubit, delays, unit=unit)
print(exp1.circuits()[0]) | ┌───┐┌──────────────┐┌──────┐ ░ ┌───┐ ░ ┌─┐
q_0: ┤ H ├┤ Delay(1[us]) ├┤ P(0) ├─░─┤ H ├─░─┤M├
└───┘└──────────────┘└──────┘ ░ └───┘ ░ └╥┘
c: 1/═════════════════════════════════════════╩═
0
| Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
We run the experiment on a simple, simulated backend, created specifically for this experiment's tutorial. | from qiskit_experiments.test.t2ramsey_backend import T2RamseyBackend
# FakeJob is a wrapper for the backend, to give it the form of a job
from qiskit_experiments.test.utils import FakeJob
import qiskit_experiments.matplotlib
from qiskit_experiments.matplotlib import pyplot, requires_matplotlib
from qiskit_experiments.m... | _____no_output_____ | Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
The resulting graph will have the form:$ f(t) = a^{-t/T_2*} \cdot cos(2 \pi f t + \phi) + b $where *t* is the delay, $T_2*$ is the decay factor, and *f* is the detuning frequency.`conversion_factor` is a scaling factor that depends on the measurement units used. It is 1E-6 here, because the unit is microseconds. | exp1.set_analysis_options(user_p0=None, plot=True)
expdata1 = exp1.run(backend=backend, shots=2000)
expdata1.block_for_results() # Wait for job/analysis to finish.
# Display the figure
display(expdata1.figure(0))
# T2* results:
t2ramsey = expdata1.analysis_results(0).data()
t2ramsey
# Frequency result:
frequency = exp... | _____no_output_____ | Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
Providing initial user estimatesThe user can provide initial estimates for the parameters to help the analysis process. Because the curve is expected to decay toward $0.5$, the natural choice for parameters $A$ and $B$ is $0.5$. Varying the value of $\phi$ will shift the graph along the x-axis. Since this is not of in... | from qiskit_experiments.library.characterization import T2RamseyAnalysis
user_p0={
"A": 0.5,
"t2ramsey": 85.0,
"f": 0.021,
"phi": 0,
"B": 0.5
}
exp_with_p0 = T2Ramsey(qubit, delays, unit=unit)
exp_with_p0.set_analysis_options(user_p0=user_p0, plot=True)
expdata_with_p0 = exp_with_p0.run(back... | _____no_output_____ | Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
The units can be changed, but the output in the result is always given in seconds. The units in the backend must be adjusted accordingly. | from qiskit.utils import apply_prefix
unit = 'ns'
delays = list(range(1000, 150000, 2000))
conversion_factor = apply_prefix(1, unit)
print(conversion_factor)
p0={"a_guess":[0.5], "t2ramsey":[80000], "f_guess":[0.00002], "phi_guess":[0.0],
"b_guess": [0.5]}
backend_in_ns = T2RamseyBackend(
... | _____no_output_____ | Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
Adding data to an existing experimentIt is possible to add data to an experiment, after the analysis of the first set of data. In the next example we add exp2 to `exp_in_ns` that we showed above. | more_delays = list(range(2000, 150000, 2000))
exp_new = T2Ramsey(qubit, more_delays, unit=unit)
exp_new.set_analysis_options(user_p0=None, plot=True)
expdata_new = exp_new.run(
backend=backend_in_ns,
experiment_data=expdata_in_ns,
shots=2000
)
expdata_new.block_for_r... | T2Ramsey: 8.006074688405924e-05
Fitted frequency: 98980008.19000898
| Apache-2.0 | docs/tutorials/t2ramsey_tutorial.ipynb | blakejohnson/qiskit-experiments |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
file_to_load = "Resources/purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)
purchase_data | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Player Count * Display the total number of players | players = purchase_data["SN"].unique()
player_count = pd.DataFrame([{"Unique User Count":len(players)}])
player_count
| _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc.* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | unique_items =len(purchase_data["Item Name"].unique())
total_revenue = purchase_data["Price"].sum()
purchases_count = len(purchase_data["Price"])
average_price = total_revenue / purchases_count
#the data frame for Analysis of the purchases
purchasing_analysis = pd.DataFrame([{"Number of Unique Items":unique_items,
... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Gender Demographics * Percentage and Count of Male Players* Percentage and Count of Female Players* Percentage and Count of Other / Non-Disclosed | #graphics summary
#Lets create a df so we can store the screen names/gender and purchase data from the script
purchaser_genders = purchase_data[["SN","Gender","Price"]].copy()
#seperate the differet genders for the players
dif_player_gen = purchaser_genders.drop_duplicates(subset=["SN","Gender"], keep="first")
dif_p... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | # THe Analysis for the purchase by gender
group_purchaser_gen = purchaser_genders.groupby(["Gender"])
purchase_cby_gen = group_purchaser_gen["Price"].count()
average_purchase_pby_gen = group_purchaser_gen["Price"].mean()
purchase_sumby_gen = group_purchaser_gen["Price"].sum()
#create the summury for purchase by gende... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Age Demographics * Establish bins for ages* Categorize the existing players using the age bins. Hint: use pd.cut()* Calculate the numbers and percentages by age group* Create a summary data frame to hold the results* Optional: round the percentage column to two decimal points* Display Age Demographics Table | ##AGE DEMOGRAPGHICS####
#Create data frame to stor names, age, and purchase data
purchaser_ages = purchase_data[["SN","Age","Price"]].copy()
#eliminate the duplicates and create a for them
dif_player_ages = purchaser_ages.drop_duplicates(subset=["SN","Age"],keep="first")
#create a bukey for storage for different ages ... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Purchasing Analysis (Age) * Bin the purchase_data data frame by age* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary d... | #Purchase Analysis
#make rows and colums labeled withthe data pulled and age from the lists
all_purchase_ab = pd.cut(purchase_data["Age"], bins=age_stg,
right=False, labels=age_lb)
purchaser_ages["Age Bin"] = all_purchase_ab
gpurchaser_acounts = purchaser_ages.groupby(["Age Bin"]).count()
gpurc... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Top Spenders * Run basic calculations to obtain the results in the table below* Create a summary data frame to hold the results* Sort the total purchase value column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame | #find the top 5 spenders
purchase_total_sum_SN = purchase_data.groupby(["SN"]).sum()
sort_purchase_total_sum_SN = purchase_total_sum_SN.sort_values("Price", ascending=False)
purchase_cby_sn = purchase_data["SN"].value_counts()
purchase_sby_sn = sort_purchase_total_sum_SN["Price"]
top_spenders = pd.DataFrame({"Purc... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns* Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value* Create a summary data frame to hold the results* Sort the purchase count column in descending order* Optional: give the disp... | #Iteams that are the most popular
items= purchase_data[["Item ID","Item Name","Price"]]
group_items = items.groupby(["Item ID","Item Name"])
purchase_cby_item = group_items["Item ID"].count()
total_purchase_vby_item = group_items["Price"].sum()
item_price = total_purchase_vby_item / purchase_cby_item
#create a df for... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Most Profitable Items * Sort the above table by total purchase value in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the data frame | ###Profitable items####
#make a copy of the most popular items table and sort by the purchase value
most_profit_items = pd.DataFrame({"Purchase Count": purchase_cby_item,
"Item Price": item_price,
"Total Purchase Value": total_purchase_vby_item})
most_profit_... | _____no_output_____ | ADSL | HeroesOfPymoli/RaulVilla.ipynb | Deathwishx89/PANDAS_CHALLENGE |
Experimental data analysis on foil open area Brian Larsen, ISR-1 Data provided by Phil Fernandes, ISR-1 2016-9-14 The setup is a foil in its holder mounted to a foil holder meant to bock incident ions. The foil has a ~0.6mm hole in it to provide a baseline. The goal is to use the relative intensity of the witness hole... | import itertools
from pprint import pprint
from operator import getitem
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
import spacepy.plot as spp
import pymc as mc
import tqdm
from MCA_file_viewer_v001 import GetMCAfile
def plot_box(x, y, c='r', lw=0.6, ax=None):
if ax is... | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Do some calculations to try and match Phil's analysis Phil's data:File name Witness cts Total cts Foil cts Open area16090203 658 4570 3912 0.00102 | total_cnts = ZZ.sum()
print('Total counts:{0} -- Phil got {1} -- remember /2'.format(total_cnts, 4570/2)) # remember we did a /2
# Is the whitness hole at x=1000, y=500?
XX.shape, YY.shape, ZZ.shape
print(ZZ[yind[0]:yind[1], xind[0]:xind[1]])
plt.figure()
plt.pcolormesh(XX[xind[0]:xind[1]], YY[yind[0]:yind[1]], ZZ[yi... | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Can we get a noise estimate? 1) Try all pixels with a value where a neighbor does not. This assumes that real holes are large enough to have a point spread function and therefore cannot be in a single pixel. | def neighbor_inds(x, y, xlim=(0,1023), ylim=(0,1023), center=False, mask=False):
"""
given an x and y index return the 8 neighbor indices
if center also return the center index
if mask return a boolean mask over the whole 2d array
"""
xi = np.clip([x + v for v in [-1, 0, 1]], xlim[0], xlim[... | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Noise estimatesNot we assume that all lone counts are noise that can be considered random and uniform over the MCP. This then provides a number of counts per MCA pixel that we can use. | n_noise = np.sum([v[1] for v in alone])
n_pixels = 1024*1024
noise_pixel = n_noise/n_pixels
print("There were a total of {0} random counts over {1} pixels, {2} cts/pixel".format(n_noise, n_pixels, noise_pixel)) | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Maybe we should consider just part of the MCP, lets get the min,max X and min,max Y where there are counts and just use that area. This will increase the cts/pixel. | minx_tmp = ZZ.sum(axis=0)
minx_tmp.shape
print(minx_tmp)
miny_tmp = ZZ.sum(axis=1)
miny_tmp.shape
print(miny_tmp)
| _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Looks to go all the way to all sides in X-Y. Work to total open area calculationsNow we can model the total open area of the foil given the noise estimate per pixel and the pixels that are a part of the witness sample and the total area.We model the observed background as Poisson with center at the real background:$ob... | Aw = np.pi*(0.2/2)**2 # mm**2
Af = 182.75 # mm**2 this is the area of the foil
W_F_ratio = Aw/Af
print(Aw, Af, W_F_ratio)
C = wit_pixels/n_pixels
D = (n_pixels-wit_pixels)/n_pixels
print('C', C, 'D', D)
nbkg = mc.Uniform('nbkg', 1, n_noise*5) # just 1 to some large number
obsnbkg = mc.Poisson('obsnbkg', nbkg, obse... | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
Run again allowing some uncertainity on witness and foil areas | _Aw = np.pi*(0.2/2)**2 # mm**2
_Af = 182.75 # mm**2 this is the area of the foil
Aw = mc.Normal('Aw', _Aw, (_Aw*0.2)**-2) # 20%
Af = mc.Normal('Af', _Af, (_Af*0.1)**-2) # 10%
print(_Aw, _Af)
C = wit_pixels/n_pixels
D = (n_pixels-wit_pixels)/n_pixels
print('C', C, 'D', D)
nbkg = mc.Uniform('nbkg', 1, n_noise*5) #... | _____no_output_____ | BSD-3-Clause | Foil Open Area/Open Area.ipynb | balarsen/pymc_learning |
1. Install DependenciesFirst install the libraries needed to execute recipes, this only needs to be done once, then click play. | !pip install git+https://github.com/google/starthinker
| _____no_output_____ | Apache-2.0 | colabs/sdf_to_bigquery.ipynb | Gregorfran/starthinker |
2. Get Cloud Project IDTo run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play. | CLOUD_PROJECT = 'PASTE PROJECT ID HERE'
print("Cloud Project Set To: %s" % CLOUD_PROJECT)
| _____no_output_____ | Apache-2.0 | colabs/sdf_to_bigquery.ipynb | Gregorfran/starthinker |
3. Get Client CredentialsTo read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play. | CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE'
print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
| _____no_output_____ | Apache-2.0 | colabs/sdf_to_bigquery.ipynb | Gregorfran/starthinker |
4. Enter SDF Download ParametersDownload SDF reports into a BigQuery table. 1. Select your filter types and the filter ideas. 1. Enter the file types using commas. 1. SDF_ will be prefixed to all tables and date appended to daily tables. 1. File types take the following format: FILE_TYPE_CAMPAIGN, FILE_TYPE_AD_GROUP,..... | FIELDS = {
'auth_write': 'service', # Credentials used for writing data.
'partner_id': '', # The sdf file types.
'file_types': [], # The sdf file types.
'filter_type': '', # The filter type for the filter ids.
'filter_ids': [], # Comma separated list of filter ids for the request.
'dataset': '', # Dat... | _____no_output_____ | Apache-2.0 | colabs/sdf_to_bigquery.ipynb | Gregorfran/starthinker |
5. Execute SDF DownloadThis does NOT need to be modified unles you are changing the recipe, click play. | from starthinker.util.project import project
from starthinker.script.parse import json_set_fields, json_expand_includes
USER_CREDENTIALS = '/content/user.json'
TASKS = [
{
'dataset': {
'auth': 'user',
'dataset': {'field': {'name': 'dataset','kind': 'string','order': 6,'default': '','description': 'D... | _____no_output_____ | Apache-2.0 | colabs/sdf_to_bigquery.ipynb | Gregorfran/starthinker |
Project: Part of Speech Tagging with Hidden Markov Models --- IntroductionPart of speech tagging is the process of determining the syntactic category of a word from the words in its surrounding context. It is often used to help disambiguate natural language phrases because it can be done quickly with high accuracy. Ta... | # Jupyter "magic methods" -- only need to be run once per kernel restart
%load_ext autoreload
%aimport helpers, tests
%autoreload 1
# import python modules -- this cell needs to be run again if you make changes to any of the files
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.display import HTML... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Step 1: Read and preprocess the dataset---We'll start by reading in a text corpus and splitting it into a training and testing dataset. The data set is a copy of the [Brown corpus](https://en.wikipedia.org/wiki/Brown_Corpus) (originally from the [NLTK](https://www.nltk.org/) library) that has already been pre-processe... | data = Dataset("tags-universal.txt", "brown-universal.txt", train_test_split=0.8)
print("There are {} sentences in the corpus.".format(len(data)))
print("There are {} sentences in the training set.".format(len(data.training_set)))
print("There are {} sentences in the testing set.".format(len(data.testing_set)))
asser... | There are 57340 sentences in the corpus.
There are 45872 sentences in the training set.
There are 11468 sentences in the testing set.
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
The Dataset InterfaceYou can access (mostly) immutable references to the dataset through a simple interface provided through the `Dataset` class, which represents an iterable collection of sentences along with easy access to partitions of the data for training & testing. Review the reference below, then run and review... | key = 'b100-38532'
print("Sentence: {}".format(key))
print("words:\n\t{!s}".format(data.sentences[key].words))
print("tags:\n\t{!s}".format(data.sentences[key].tags)) | Sentence: b100-38532
words:
('Perhaps', 'it', 'was', 'right', ';', ';')
tags:
('ADV', 'PRON', 'VERB', 'ADJ', '.', '.')
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
**Note:** The underlying iterable sequence is **unordered** over the sentences in the corpus; it is not guaranteed to return the sentences in a consistent order between calls. Use `Dataset.stream()`, `Dataset.keys`, `Dataset.X`, or `Dataset.Y` attributes if you need ordered access to the data. Counting Unique ElementsY... | print("There are a total of {} samples of {} unique words in the corpus."
.format(data.N, len(data.vocab)))
print("There are {} samples of {} unique words in the training set."
.format(data.training_set.N, len(data.training_set.vocab)))
print("There are {} samples of {} unique words in the testing set."
... | There are a total of 1161192 samples of 56057 unique words in the corpus.
There are 928458 samples of 50536 unique words in the training set.
There are 232734 samples of 25112 unique words in the testing set.
There are 5521 words in the test set that are missing in the training set.
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Accessing word and tag SequencesThe `Dataset.X` and `Dataset.Y` attributes provide access to ordered collections of matching word and tag sequences for each sentence in the dataset. | # accessing words with Dataset.X and tags with Dataset.Y
for i in range(2):
print("Sentence {}:".format(i + 1), data.X[i])
print()
print("Labels {}:".format(i + 1), data.Y[i])
print() | Sentence 1: ('Mr.', 'Podger', 'had', 'thanked', 'him', 'gravely', ',', 'and', 'now', 'he', 'made', 'use', 'of', 'the', 'advice', '.')
Labels 1: ('NOUN', 'NOUN', 'VERB', 'VERB', 'PRON', 'ADV', '.', 'CONJ', 'ADV', 'PRON', 'VERB', 'NOUN', 'ADP', 'DET', 'NOUN', '.')
Sentence 2: ('But', 'there', 'seemed', 'to', 'be', 'som... | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Accessing (word, tag) SamplesThe `Dataset.stream()` method returns an iterator that chains together every pair of (word, tag) entries across all sentences in the entire corpus. | # use Dataset.stream() (word, tag) samples for the entire corpus
print("\nStream (word, tag) pairs:\n")
for i, pair in enumerate(data.stream()):
print("\t", pair)
if i > 5: break |
Stream (word, tag) pairs:
('Mr.', 'NOUN')
('Podger', 'NOUN')
('had', 'VERB')
('thanked', 'VERB')
('him', 'PRON')
('gravely', 'ADV')
(',', '.')
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
For both our baseline tagger and the HMM model we'll build, we need to estimate the frequency of tags & words from the frequency counts of observations in the training corpus. In the next several cells you will complete functions to compute the counts of several sets of counts. Step 2: Build a Most Frequent Class tag... | def pair_counts(sequences_A, sequences_B):
"""Return a dictionary keyed to each unique value in the first sequence list
that counts the number of occurrences of the corresponding value from the
second sequences list.
For example, if sequences_A is tags and sequences_B is the corresponding
words... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
IMPLEMENTATION: Most Frequent Class TaggerUse the `pair_counts()` function and the training dataset to find the most frequent class label for each word in the training data, and populate the `mfc_table` below. The table keys should be words, and the values should be the appropriate tag string.The `MFCTagger` class is ... | # Create a lookup table mfc_table where mfc_table[word] contains the tag label most frequently assigned to that word
from collections import namedtuple
FakeState = namedtuple("FakeState", "name")
class MFCTagger:
# NOTE: You should not need to modify this class or any of its methods
missing = FakeState(name="... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Making Predictions with a ModelThe helper functions provided below interface with Pomegranate network models & the mocked MFCTagger to take advantage of the [missing value](http://pomegranate.readthedocs.io/en/latest/nan.html) functionality in Pomegranate through a simple sequence decoding function. Run these function... | def replace_unknown(sequence):
"""Return a copy of the input sequence where each unknown word is replaced
by the literal string value 'nan'. Pomegranate will ignore these values
during computation.
"""
return [w if w in data.training_set.vocab else 'nan' for w in sequence]
def simplify_decoding(X, ... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Example Decoding Sequences with MFC Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, mfc_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Evaluating Model AccuracyThe function below will evaluate the accuracy of the MFC tagger on the collection of all sentences from a text corpus. | def accuracy(X, Y, model):
"""Calculate the prediction accuracy by using the model to decode each sequence
in the input X and comparing the prediction with the true labels in Y.
The X should be an array whose first dimension is the number of sentences to test,
and each element of the array should b... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Evaluate the accuracy of the MFC taggerRun the next cell to evaluate the accuracy of the tagger on the training and test corpus. | mfc_training_acc = accuracy(data.training_set.X, data.training_set.Y, mfc_model)
print("training accuracy mfc_model: {:.2f}%".format(100 * mfc_training_acc))
mfc_testing_acc = accuracy(data.testing_set.X, data.testing_set.Y, mfc_model)
print("testing accuracy mfc_model: {:.2f}%".format(100 * mfc_testing_acc))
assert ... | training accuracy mfc_model: 95.71%
testing accuracy mfc_model: 93.13%
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Step 3: Build an HMM tagger---The HMM tagger has one hidden state for each possible tag, and parameterized by two distributions: the emission probabilties giving the conditional probability of observing a given **word** from each hidden state, and the transition probabilities giving the conditional probability of movi... | def unigram_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequence list that
counts the number of occurrences of the value in the sequences list. The sequences
collection should be a 2-dimensional array.
For example, if the tag NOUN appears 275558 times over all ... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
IMPLEMENTATION: Bigram CountsComplete the function below to estimate the co-occurrence frequency of each pair of symbols in each of the input sequences. These counts are used in the HMM model to estimate the bigram probability of two tags from the frequency counts according to the formula: $$P(tag_2|tag_1) = \frac{C(t... | import itertools
def pairwise(iterable):
t, t_1 = itertools.tee(iterable)
next(t_1, 'end')
return zip(t, t_1)
def bigram_counts(sequences):
"""Return a dictionary keyed to each unique PAIR of values in the input sequences
list that counts the number of occurrences of pair in the sequences list. The... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
IMPLEMENTATION: Sequence Starting CountsComplete the code below to estimate the bigram probabilities of a sequence starting with each tag. | def starting_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the beginning of
a sequence.
For example, if 8093 sequences start with NOUN, then you should return a
dictionary such that y... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
IMPLEMENTATION: Sequence Ending CountsComplete the function below to estimate the bigram probabilities of a sequence ending with each tag. | def ending_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the end of
a sequence.
For example, if 18 sequences end with DET, then you should return a
dictionary such that your_starting_... | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
IMPLEMENTATION: Basic HMM TaggerUse the tag unigrams and bigrams calculated above to construct a hidden Markov tagger.- Add one state per tag - The emission distribution at each state should be estimated with the formula: $P(w|t) = \frac{C(t, w)}{C(t)}$- Add an edge from the starting state `basic_model.start` to ea... | basic_model = HiddenMarkovModel(name="base-hmm-tagger")
# TODO: create states with emission probability distributions P(word | tag) and add to the model
# (Hint: you may need to loop & create/add new states)
tags = [tag for word, tag in data.stream()]
words = [word for word, tag in data.stream()]
tags_count = unigram... | training accuracy basic hmm model: 97.51%
testing accuracy basic hmm model: 96.14%
| MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Example Decoding Sequences with the HMM Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, basic_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Finishing the project---**Note:** **SAVE YOUR NOTEBOOK**, then run the next cell to generate an HTML copy. You will zip & submit both this file and the HTML copy for review. | !!jupyter nbconvert *.ipynb | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
Step 4: [Optional] Improving model performance---There are additional enhancements that can be incorporated into your tagger that improve performance on larger tagsets where the data sparsity problem is more significant. The data sparsity problem arises because the same amount of data split over more tags means there ... | import nltk
from nltk import pos_tag, word_tokenize
from nltk.corpus import brown
nltk.download('brown')
training_corpus = nltk.corpus.brown
training_corpus.tagged_sents()[0] | _____no_output_____ | MIT | HMM Tagger.ipynb | bijanh/NLP-Proj-1 |
TensorFlow TutorialWelcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras... | import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
%matplotlib inline
np.random.seed(1) | _____no_output_____ | MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Now that you have imported the library, we will walk you through its different applications. You will start with an example, where we compute for you the loss of one training example. $$loss = \mathcal{L}(\hat{y}, y) = (\hat y^{(i)} - y^{(i)})^2 \tag{1}$$ | y_hat = tf.constant(36, name='y_hat') # Define y_hat constant. Set to 36.
y = tf.constant(39, name='y') # Define y. Set to 39
loss = tf.Variable((y - y_hat)**2, name='loss') # Create a variable for the loss
init = tf.global_variables_initializer() # When init is run later (sessi... | 9
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Writing and running programs in TensorFlow has the following steps:1. Create Tensors (variables) that are not yet executed/evaluated. 2. Write operations between those Tensors.3. Initialize your Tensors. 4. Create a Session. 5. Run the Session. This will run the operations you'd written above. Therefore, when we create... | a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c) | Tensor("Mul:0", shape=(), dtype=int32)
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
As expected, you will not see 20! You got a tensor saying that the result is a tensor that does not have the shape attribute, and is of type "int32". All you did was put in the 'computation graph', but you have not run this computation yet. In order to actually multiply the two numbers, you will have to create a sessio... | sess = tf.Session()
print(sess.run(c)) | 20
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Great! To summarize, **remember to initialize your variables, create a session and run the operations inside the session**. Next, you'll also have to know about placeholders. A placeholder is an object whose value you can specify only later. To specify values for a placeholder, you can pass in values by using a "feed d... | # Change the value of x in the feed_dict
x = tf.placeholder(tf.int64, name = 'x')
print(sess.run(2 * x, feed_dict = {x: 3}))
sess.close() | 6
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
When you first defined `x` you did not have to specify a value for it. A placeholder is simply a variable that you will assign data to only later, when running the session. We say that you **feed data** to these placeholders when running the session. Here's what's happening: When you specify the operations needed for a... | # GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- r... | result = [[-2.15657382]
[ 2.95891446]
[-1.08926781]
[-0.84538042]]
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
*** Expected Output ***: **result**[[-2.15657382] [ 2.95891446] [-1.08926781] [-0.84538042]] 1.2 - Computing the sigmoid Great! You just implemented a linear function. Tensorflow offers a variety of commonly used neural network functions like `tf.sigmoid` and `tf.softmax`. For this exercise lets compute the sigmoi... | # GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
### START CODE HERE ### ( approx. 4 lines of code)
# Create a placeholder for x. Name it 'x'.
x = tf.pl... | sigmoid(0) = 0.5
sigmoid(12) = 0.999994
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
*** Expected Output ***: **sigmoid(0)**0.5 **sigmoid(12)**0.999994 **To summarize, you how know how to**:1. Create placeholders2. Specify the computation graph corresponding to operations you want to compute3. Create the session4. Run the session, using a feed dictionary if necessary to specify placeholder variable... | # GRADED FUNCTION: cost
def cost(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "... | cost = [ 1.00538719 1.03664076 0.41385433 0.39956617]
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
** Expected Output** : **cost** [ 1.00538719 1.03664088 0.41385433 0.39956614] 1.4 - Using One Hot encodingsMany times in deep learning you will have a y vector with numbers ranging from 0 to C-1, where C is the number of classes. If C is for example 4, t... | # GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
... | one_hot = [[ 0. 0. 0. 1. 0. 0.]
[ 1. 0. 0. 0. 0. 1.]
[ 0. 1. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 0. 0.]]
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **one_hot** [[ 0. 0. 0. 1. 0. 0.] [ 1. 0. 0. 0. 0. 1.] [ 0. 1. 0. 0. 1. 0.] [ 0. 0. 1. 0. 0. 0.]] 1.5 - Initialize with zeros and onesNow you will learn how to initialize a vector of zeros and ones. The function you w... | # GRADED FUNCTION: ones
def ones(shape):
"""
Creates an array of ones of dimension shape
Arguments:
shape -- shape of the array you want to create
Returns:
ones -- array containing only ones
"""
### START CODE HERE ###
# Create "ones" tensor using tf.ones(..... | ones = [ 1. 1. 1.]
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output:** **ones** [ 1. 1. 1.] 2 - Building your first neural network in tensorflowIn this part of the assignment you will build a neural network using tensorflow. Remember that there are two parts to implement a tensorflow model:- Create the com... | # Loading the dataset
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() | _____no_output_____ | MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Change the index below and run the cell to visualize some examples in the dataset. | # Example of a picture
index = 0
plt.imshow(X_train_orig[index])
print ("y = " + str(np.squeeze(Y_train_orig[:, index]))) | y = 5
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
As usual you flatten the image dataset, then normalize it by dividing by 255. On top of that, you will convert each label to a one-hot vector as shown in Figure 1. Run the cell below to do so. | # Flatten the training and test images
X_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T
X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T
# Normalize image vectors
X_train = X_train_flatten/255.
X_test = X_test_flatten/255.
# Convert training and test labels to one hot matrices
Y_train... | number of training examples = 1080
number of test examples = 120
X_train shape: (12288, 1080)
Y_train shape: (6, 1080)
X_test shape: (12288, 120)
Y_test shape: (6, 120)
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Note** that 12288 comes from $64 \times 64 \times 3$. Each image is square, 64 by 64 pixels, and 3 is for the RGB colors. Please make sure all these shapes make sense to you before continuing. **Your goal** is to build an algorithm capable of recognizing a sign with high accuracy. To do so, you are going to build a t... | # GRADED FUNCTION: create_placeholders
def create_placeholders(n_x, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288)
n_y -- scalar, number of classes (from 0 to 5, so -> 6)
Returns:... | X = Tensor("Placeholder:0", shape=(12288, ?), dtype=float32)
Y = Tensor("Placeholder_1:0", shape=(6, ?), dtype=float32)
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **X** Tensor("Placeholder_1:0", shape=(12288, ?), dtype=float32) (not necessarily Placeholder_1) **Y** Tensor("Placeholder_2:0", shape=(10, ?), dtype=float32) (not necessarily Placeholder_2) ... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters():
"""
Initializes parameters to build a neural network with tensorflow. The shapes are:
W1 : [25, 12288]
b1 : [25, 1]
W2 : [12, 25]
b2 : [12, 1]
... | W1 = <tf.Variable 'W1:0' shape=(25, 12288) dtype=float32_ref>
b1 = <tf.Variable 'b1:0' shape=(25, 1) dtype=float32_ref>
W2 = <tf.Variable 'W2:0' shape=(12, 25) dtype=float32_ref>
b2 = <tf.Variable 'b2:0' shape=(12, 1) dtype=float32_ref>
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **W1** **b1** **W2** **b2** As expected, the parameters ... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX
Arguments:
X -- input dataset placeholder, of shape (input size, number of examples)
parameters -- python d... | Z3 = Tensor("Add_2:0", shape=(6, ?), dtype=float32)
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **Z3** Tensor("Add_2:0", shape=(6, ?), dtype=float32) You may have noticed that the forward propagation doesn't output any cache. You will understand why below, when we get to brackpropagation. 2.4 Compute costAs seen before, it is very ... | # GRADED FUNCTION: compute_cost
def compute_cost(Z3, Y):
"""
Computes the cost
Arguments:
Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y -- "true" labels vector placeholder, same shape as Z3
Returns:
cost - Tensor of the c... | cost = Tensor("Mean:0", shape=(), dtype=float32)
| MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **cost** Tensor("Mean:0", shape=(), dtype=float32) 2.5 - Backward propagation & parameter updatesThis is where you become grateful to programming frameworks. All the backpropagation and the parameters update is taken care of in 1 line of... | def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 1... | _____no_output_____ | MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Run the following cell to train your model! On our machine it takes about 5 minutes. Your "Cost after epoch 100" should be 1.016458. If it's not, don't waste time; interrupt the training by clicking on the square (⬛) in the upper bar of the notebook, and try to correct your code. If it is the correct cost, take a break... | parameters = model(X_train, Y_train, X_test, Y_test) | Cost after epoch 0: 1.877091
Cost after epoch 100: 1.469517
Cost after epoch 200: 1.290366
Cost after epoch 300: 1.157710
Cost after epoch 400: 1.049604
Cost after epoch 500: 0.955978
Cost after epoch 600: 0.873848
Cost after epoch 700: 0.802411
Cost after epoch 800: 0.737561
Cost after epoch 900: 0.679775
Cost after e... | MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
**Expected Output**: **Train Accuracy** 0.999074 **Test Accuracy** 0.716667 Amazing, your algorithm can recognize a sign representing a figure between 0 and 5 with 71.7% accuracy.**Insights**:- Your mod... | import scipy
from PIL import Image
from scipy import ndimage
## START CODE HERE ## (PUT YOUR IMAGE NAME)
my_image = "thumbs_up.jpg"
## END CODE HERE ##
# We preprocess your image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(... | _____no_output_____ | MIT | 02-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week3/answer-Tensorflow+Tutorial.ipynb | Ulysses-WJL/Coursera-Deep-Learning-deeplearning.ai |
Evaluate Amazon Video Games Review Dataset | # ndjson to handle newline delimited json
!pip install ndjson
# update imbalanced-learn lib on colab
!pip install --upgrade imbalanced-learn
# all imports and related
%matplotlib inline
import pandas as pd
import numpy as np
import altair as alt
import ndjson
from collections import Counter
from imblearn.under_sampl... | dataset X shape: (497577, 2) type: <class 'numpy.ndarray'>
label y shape: (497577,) type: <class 'numpy.ndarray'>
| MIT | create_dataset.ipynb | oonid/growth-hacking-with-nlp-sentiment-analysis |
Generating small_corpus | # predefined sampling strategy
sampling_strategy = {1.0: 1500, 2.0: 500, 3.0: 500, 4.0: 500, 5.0: 1500}
random_state = 42 # to get identical results with sample solution
rus = RandomUnderSampler(random_state=random_state,
sampling_strategy=sampling_strategy)
X_res, y_res = rus.fit_resample(X... | _____no_output_____ | MIT | create_dataset.ipynb | oonid/growth-hacking-with-nlp-sentiment-analysis |
Generating big_corpus | random_state = 42 # to get identical results with sample solution
np.random.seed(random_state)
# get 100.000 on random ratings (1-5) as numpy array
random_ratings = np.random.randint(low=1, high=6, size=100000)
# create sampling strategy by count total ratings on random_ratings (dataframe)
unique, counts = np.unique(... | _____no_output_____ | MIT | create_dataset.ipynb | oonid/growth-hacking-with-nlp-sentiment-analysis |
Project DescriptionAnother CV2 tutorial this one from https://pythonprogramming.net/loading-images-python-opencv-tutorial/ | #http://tsaith.github.io/record-video-with-python-3-opencv-3-on-osx.html
import numpy as np
import cv2
cap = cv2.VideoCapture(0) # Capture video from camera
# Get the width and height of frame
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)
# Define the co... | _____no_output_____ | Apache-2.0 | VideotoImages/Video with LIFX Tiles.ipynb | netmanchris/pylifxtiles |
Writting stuff on an image | import numpy as np
import cv2
img = cv2.imread('watch.jpg',cv2.IMREAD_COLOR)
cv2.line(img,(0,0),(200,300),(255,255,255),50)
cv2.rectangle(img,(500,250),(1000,500),(0,0,255),15)
cv2.circle(img,(447,63), 63, (0,255,0), -1)
pts = np.array([[100,50],[200,300],[700,200],[500,100]], np.int32)
pts = pts.reshape((-1,1,2))
cv2... | _____no_output_____ | Apache-2.0 | VideotoImages/Video with LIFX Tiles.ipynb | netmanchris/pylifxtiles |
Hierarchical Clustering LabIn this notebook, we will be using sklearn to conduct hierarchical clustering on the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) which contains 4 dimensions/attributes and 150 samples. Each sample is labeled as one of the three type of Iris flowers.In this exercise, we'll ig... | from sklearn import datasets
iris = datasets.load_iris() | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
A look at the first 10 samples in the dataset | iris.data[:10] | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
```iris.target``` contains the labels that indicate which type of Iris flower each sample is | iris.target | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
2. ClusteringLet's now use sklearn's [```AgglomerativeClustering```](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html) to conduct the heirarchical clustering | from sklearn.cluster import AgglomerativeClustering
# Hierarchical clustering
# Ward is the default linkage algorithm, so we'll start with that
ward = AgglomerativeClustering(n_clusters=3)
ward_pred = ward.fit_predict(iris.data) | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Let's also try complete and average linkages**Exercise**:* Conduct hierarchical clustering with complete linkage, store the predicted labels in the variable ```complete_pred```* Conduct hierarchical clustering with average linkage, store the predicted labels in the variable ```avg_pred```Note: look at the documentation... | # Hierarchical clustering using complete linkage
# TODO: Create an instance of AgglomerativeClustering with the appropriate parameters
complete = AgglomerativeClustering(n_clusters=3, linkage = 'complete')
# Fit & predict
# TODO: Make AgglomerativeClustering fit the dataset and predict the cluster labels
complete_pred ... | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.