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
3D棒グラフの表示
v = cesiumpy.Viewer() for i, row in df.iterrows(): l = row['施設_収容人数[総定員]人数'] cyl = cesiumpy.Cylinder(position=[row['施設_経度'], row['施設_緯度'] ], length=l*10,topRadius=50, bottomRadius=50, material='aqua') v.entities.add(cyl) v
_____no_output_____
Apache-2.0
Cesium_Advent_Calendar_3rd.ipynb
tkama/hello_cesiumpy
_____no_output_____
Apache-2.0
Untitled2.ipynb
Asha-ai/BERT_abstractive_proj
Merge filesinto one printable pdf
# Define naming pattern pattern = r'C:\Users\Ol\Documents\EXPERIMENTS\ACT_ID\Materials\PDF\2\*.pdf' # Generate files list pdfs_list = glob.glob(pattern) # Merge and write the output file merger = PdfFileMerger() for f in pdfs_list: merger.append(PdfFileReader(f), 'rb') merger.write(r'C:\Users\Ol\Documents\EXPERIMENTS\ACT_ID\Materials\PDF\FAU_UW_project2.pdf')
_____no_output_____
MIT
Vallacher_PdfGen.ipynb
AlxndrMlk/PDF_generator
About Dipoles in MEG and EEGFor an explanation of what is going on in the demo and background informationabout magentoencephalography (MEG) and electroencephalography (EEG) ingeneral, let's walk through some code. To execute this code, you'll needto have a working version of python with ``mne`` installed, see the`quick-start` documentation for instructions. You'll need the developmentversion, so you'll need to do``pip install git+https://github.com/mne-tools/mne-python.git`` You'll alsoneed to install the requirements such as with``pip install -r requirements.txt``.
# Author: Alex Rockhill <aprockhill@mailbox.org> # # License: BSD-3-Clause
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Let's start by importing the dependencies we'll need.
import os.path as op # comes with python and helps naviagte to files import numpy as np # a scientific computing package with arrays import matplotlib.pyplot as plt # a plotting library import mne # our main analysis software package from nilearn.plotting import plot_anat # this package plots brains
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
BackgroundMEG and EEG researchers record very small electromagentic potentialsgenerated by the brain from outside the head. When it comes from therecording devices, it looks like this (there are a lot of channelsso only a subset are shown):
data_path = mne.datasets.sample.data_path() # get the sample data path raw = mne.io.read_raw( # navigate to some raw sample data op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')) raw_plot = raw.copy() # make a copy to modify for plotting raw_plot.pick_channels(raw.ch_names[::10]) # pick only every tenth channel raw_plot.plot(n_channels=len(raw_plot.ch_names), duration=1, # only a small, 1 second time window start=50, # start part way in )
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
The goal of MEG and EEG researchers is to try and understand how activityin the brain changes as we respond to stimuli in our environment andperform behaviors. To do that, researchers will often use magnetic resonance(MR) to create an image of the research subject's brain. These imageslook like this:
# first, get a T1-weighted MR scan file from the MNE example dataset T1_fname = op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz') plot_anat(T1_fname) # now we can plot it
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
The T1 MR image can be used to figure out where the surfaces of thebrain skull and scalp are as well as label the parts of the brainin the image using Freesurfer. The command below does this (it takes8 hours so I wouldn't recommend executing it now but it has alreadybeen done for you in the mne sample data, see `here`_ forhow to install Freesurfer):.. code-block:: bash recon-all -subjid sample -sd $DATA_PATH/subjects -i $T1_FNAME -all Now let's put it all together and see the problem that MEG and EEGresearchers face in figuring out what's going on inside the brain fromelectromagnetic potentials on the surface of the scalp. As you can see below,there are a lot of MEG and EEG sensors and they cover a large portion of thehead but its not readily apparent how much of each brain area each sensorrecords from and how to separate the summed activity from all the brain areasthat is recorded by each sensor into components for each brain area:NoteThe sensor positions don't come aligned to the MR image since they are recorded by a different device so we need to a transformation matrix to transform them from the coordinate frame they are in to MR coordinates. This can be done with :func:`mne.gui.coregistration` to generate the ``trans`` file that is loaded below.
# the subjects_dir is where Freesurfer stored all the surface files subjects_dir = op.join(data_path, 'subjects') trans = mne.read_trans(op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif')) # the main plotter for mne, the brain object brain = mne.viz.Brain(subject_id='sample', hemi='both', surf='pial', subjects_dir=subjects_dir) brain.add_skull(alpha=0.5) # alpha sets transparency brain.add_head(alpha=0.5) brain.add_sensors(raw.info, trans) # set a nice view to show brain.show_view(azimuth=120, elevation=90, distance=500)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Making a Source Space and Forward ModelFirst let's setup a space of vertices within the brain that we will consideras the sources of signal. In a real brain, there are hundreds of billionsof cells but we don't have the resolution with only hundreds of sensors todetermine the activity of each cell, so, instead, we'll choose a regularlysampled grid of sources that represent the summed activity of tens ofthousands of cells. In most analyses in publications, the source space hasaround 8000 vertices, but, for this example, we'll use a smaller sourcespace for demonstration. First, we would need to make a boundary element model (BEM) to account fordifferences in conductivity of the brain, skull and scalp. This can bedone with :func:`mne.make_bem_model` but, in this case, we'll just loada pre-computed model. We'll also load the solution to the BEM model for howdifferent conductivities of issues effect current dipoles as they passthrough each of the layers, but this can be computed with:func:`mne.make_bem_solution`.
bem_fname = op.join(subjects_dir, 'sample', 'bem', 'sample-5120-5120-5120-bem.fif') # load a pre-computed solution the how the sources within the brain will # be affected by the different conductivities bem_sol = op.join(subjects_dir, 'sample', 'bem', 'sample-5120-5120-5120-bem-sol.fif') # plot it, it's saved out in a standard location, # so we don't have to pass the path mne.viz.plot_bem(subject='sample', subjects_dir=op.join(data_path, 'subjects'), slices=np.linspace(45, 200, 12).round().astype(int))
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Making a DipoleNow, we're ready to make a dipole and see how its current will be recordedat the scalp with MEG and EEG.NoteYou can use ``print(mne.Dipole.__doc__)`` to print the arguments that are required by ``mne.Dipole`` or any other class, method or function.
# make a dipole within the temporal lobe pointing superiorly, # fake a goodness-of-fit number dip_pos = [-0.0647572, 0.01315963, 0.07091921] dip = mne.Dipole(times=[0], pos=[dip_pos], amplitude=[3e-8], ori=[[0, 0, 1]], gof=50) # plot it! brain = mne.viz.Brain(subject_id='sample', hemi='both', surf='pial', subjects_dir=subjects_dir, alpha=0.25) brain.add_dipole(dip, trans, scales=10) brain.show_view(azimuth=150, elevation=60, distance=500)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Simulating Sensor DataWe're ready to compute a forward operator using the BEM to make the so-calledleadfield matrix which multiplies activity at the dipole to give themodelled the activity at the sensors. We can then use this to simulate evokeddata.
fwd, stc = mne.make_forward_dipole( dipole=dip, bem=bem_sol, info=raw.info, trans=trans) # we don't have a few things like the covarience matrix or a number of epochs # to average so we use these arguments for a reasonable solution evoked = mne.simulation.simulate_evoked( fwd, stc, raw.info, cov=None, nave=np.inf) # Now we can see what it would look like at the sensors fig, axes = plt.subplots(1, 3, figsize=(6, 4)) # make a figure with 3 subplots # use zip to iterate over axes and channel types at the same time for ax, ch_type in zip(axes, ('grad', 'mag', 'eeg')): # we're just looking at the relative pattern so we won't use a colorbar evoked.plot_topomap(times=[0], ch_type=ch_type, axes=ax, colorbar=False) ax.set_title(ch_type)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Wrapping UpWe covered some good intuition but there's lots more to learn! The main thingis that MEG and EEG researchers generally don't have the information aboutwhat's going on inside the brain, that's what they are trying to predict. Toreverse this process, you need to invert the forward solution (tutorial:`tut-viz-stcs`). There is tons more to explore in the MNE `tutorials`_ and `examples`_ pages. Let's leave off bysetting up a source space of many different dipoles and seeing theirdifferent activities manifest on the scalp as measured by the sensors.
src = mne.setup_volume_source_space( subject='sample', pos=20, # in mm bem=bem_fname, subjects_dir=subjects_dir) # make the leadfield matrix fwd = mne.make_forward_solution( raw.info, trans=trans, src=src, bem=bem_sol) # plot our setup brain = mne.viz.Brain(subject_id='sample', hemi='both', surf='pial', subjects_dir=subjects_dir, alpha=0.25) brain.add_volume_labels(alpha=0.25, colors='gray') brain.add_forward(fwd, trans, scale=3) brain.show_view(azimuth=30, elevation=90, distance=500)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Plot the same solution using a source space of dipoles
# take the source space from the forward model because some of the # vertices are excluded from the vertices in src n_dipoles = fwd['source_rr'].shape[0] # rr is the vertex positions # find the closest dipole to the one we used before (it was in this # source space) using the euclidean distance (np.linalg.norm) idx = np.argmin(np.linalg.norm(fwd['source_rr'] - dip_pos, axis=1)) # make an empty matrix of zeros data = np.zeros((n_dipoles, 3, 1)) data[idx, 2, 0] = 3e-8 # make the same dipole as before # this is the format that vertiex numbers are stored in vertices = [fwd['src'][0]['vertno']] stc = mne.VolVectorSourceEstimate(data, vertices=vertices, subject='sample', tmin=0, tstep=1) evoked = mne.simulation.simulate_evoked( fwd, stc, raw.info, cov=None, nave=np.inf) # confirm our replication fig, axes = plt.subplots(1, 3, figsize=(6, 4)) # make a figure with 3 subplots for ax, ch_type in zip(axes, ('grad', 'mag', 'eeg')): evoked.plot_topomap(times=[0], ch_type=ch_type, axes=ax, colorbar=False) ax.set_title(ch_type)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Now, go crazy and simulate a bunch of random dipoles
np.random.seed(88) # always seed random number generation for reproducibility stc.data = np.random.random(stc.data.shape) * 3e-8 - 1.5e-8 evoked = mne.simulation.simulate_evoked( fwd, stc, raw.info, cov=None, nave=np.inf) # now that's a complicated faked brain pattern, fortunately brain activity # is much more correlated (neighboring areas have similar activity) which # makes results a bit easier to interpret fig, axes = plt.subplots(1, 3, figsize=(6, 4)) # make a figure with 3 subplots for ax, ch_type in zip(axes, ('grad', 'mag', 'eeg')): evoked.plot_topomap(times=[0], ch_type=ch_type, axes=ax, colorbar=False) ax.set_title(ch_type)
_____no_output_____
BSD-3-Clause
doc/auto_examples/plot_tutorial.ipynb
alexrockhill/dipole-simulator2
Topics of Block Chain
_topics=[ 'Philosophical: impact on society', 'Scientific: algorithms, computer science, math)', 'Commerce: changes to industry', 'Capital: risk / reward of allocation strategies', 'Mechanical: code, servers, data centers', ] _w=300 _h=50 _s=10 svg_document = svgwrite.Drawing(filename = "test-svgwrite.svg", size = ("800px", "600px")) for _index, _topic in enumerate(_topics): svg_document.add( svg_document.rect( insert = ( 20, _s*(_index+1)+_h*_index, ), size = ( '{:d}px'.format(_w), '{:d}px'.format(_h), ), stroke_width = '1', stroke = 'blue', fill = 'rgb(255,255,255)', ), ) svg_document.add( svg_document.text( _topic, insert = ( 30, _s*(_index+1)+_h*_index+28, ), style = 'font-size:10px; font-family:monospace' ) ) svg_document.save() with open('test.png', 'wb') as png_file: png_file.write(cairosvg.svg2png(url='test-svgwrite.svg'))
_____no_output_____
MIT
slide_illustration.ipynb
darpanbiswas/chain
Se inicializa una red neuronal usando función de activación de tangente hiperbólica, tasa de aprendizaje de 0.1 y 44 neuronas en capa oculta.Se entrena con dos instancias de entrenamiento (X e y) usando el método fit sobre la red neuronal.
# Inicializo red neuronal con scikit clf = MLPClassifier(solver='lbfgs', activation='tanh', alpha=1e-4, hidden_layer_sizes=(44), random_state=1, learning_rate_init=.1) # Genero un array de vectores de input, de tamaño 64 y valores de [0,2] X = [] for i in range(4): X.append(numpy.random.randint(3, size=64)) # X = numpy.random.randint(3, size=64).tolist() # X.append(5) # X.append(4) # X = X.reshape(1,-1) y = [0, 1, -1, 0] # Se entrena con X e Y a la red clf.fit(X, y) X = [] for i in range(4): X.append(numpy.random.randint(3, size=64)) y = [-1, 0, -1, 1] # Se entrena nuevamente clf.fit(X, y) # clf.predict([[0., 0.], [1., 1.], [2., 1.], [1., 2.], [0., 1.5]])
_____no_output_____
MIT
Lab1/Neural network test.ipynb
marcciosilva/maa
Ejemplo de cómo evaluar un vector de entrada nuevo (lo que sería un tablero de Othello) con la red neuronal.
newBoard = numpy.random.randint(3, size=64) newBoard = newBoard.reshape(1,-1) clf.predict(newBoard)
_____no_output_____
MIT
Lab1/Neural network test.ipynb
marcciosilva/maa
Ejemplo de como persistir red neuronal entrenada a un archivo en la ruta del notebook.
neuralNetwork = MLPClassifier(solver='lbfgs', activation='tanh', alpha=1e-4, hidden_layer_sizes=(44), random_state=1, learning_rate_init=.1) joblib.dump(neuralNetwork, 'red-neuronal-test.pkl')
_____no_output_____
MIT
Lab1/Neural network test.ipynb
marcciosilva/maa
Segmentation This notebook shows how to use Stardist (Object Detection with Star-convex Shapes) as a part of a segmentation-classification-tracking analysis pipeline. The sections of this notebook are as follows:1. Load images2. Load model of choice and segment an initial image to test Stardist parameters3. Batch segment a sequence of imagesThe data used in this notebook is timelapse microscopy data with h2b-gfp/rfp markers that show the spatial extent of the nucleus and it's mitotic state. This notebook uses the dask octopuslite image loader from the CellX/Lowe lab project.
import matplotlib.pyplot as plt import numpy as np import os from octopuslite import DaskOctopusLiteLoader from stardist.models import StarDist2D from stardist.plot import render_label from csbdeep.utils import normalize from tqdm.auto import tqdm from skimage.io import imsave import json from scipy import ndimage as nd %matplotlib inline plt.rcParams['figure.figsize'] = [18,8]
_____no_output_____
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
1. Load images
# define experiment ID and select a position expt = 'ND0011' pos = 'Pos6' # point to where the data is root_dir = '/home/nathan/data' image_path = f'{root_dir}/{expt}/{pos}/{pos}_images' # lazily load imagesdd images = DaskOctopusLiteLoader(image_path, remove_background = True) images.channels
Using cropping: (1200, 1600)
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
Set segmentation channel and load test image
# segmentation channel segmentation_channel = images.channels[3] # set test image index frame = 1000 # load test image irfp = images[segmentation_channel.name][frame].compute() # create 1-channel XYC image img = np.expand_dims(irfp, axis = -1) img.shape
_____no_output_____
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
2. Load model and test segment single image
model = StarDist2D.from_pretrained('2D_versatile_fluo') model
Found model '2D_versatile_fluo' for 'StarDist2D'. Loading network weights from 'weights_best.h5'. Loading thresholds from 'thresholds.json'. Using default values: prob_thresh=0.479071, nms_thresh=0.3.
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
2.1 Test run and display initial results
# initialise test segmentation labels, details = model.predict_instances(normalize(img)) # plot input image and prediction plt.clf() plt.subplot(1,2,1) plt.imshow(normalize(img[:,:,0]), cmap="PiYG") plt.axis("off") plt.title("input image") plt.subplot(1,2,2) plt.imshow(render_label(labels, img = img)) plt.axis("off") plt.title("prediction + input overlay") plt.show()
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
3. Batch segment a whole stack of images When you segment a whole data set you do not want to apply any image transformation. This is so that when you load images and masks later on you can apply the same transformation. You can apply a crop but note that you need to be consistent with your use of the crop from this point on, otherwise you'll get a shift.
for expt in tqdm(['ND0009', 'ND0010', 'ND0011']): for pos in tqdm(['Pos0', 'Pos1', 'Pos2', 'Pos3', 'Pos4']): print('Starting experiment position:', expt, pos) # load images image_path = f'{root_dir}/{expt}/{pos}/{pos}_images' images = DaskOctopusLiteLoader(image_path, remove_background = True) # iterate over images filenames for fn in tqdm(images.files(segmentation_channel.name)): # compile 1-channel into XYC array img = np.expand_dims(imread(fn), axis = -1) # predict labels labels, details = model.predict_instances(normalize(img)) # set filename as mask format (channel099) fn = fn.replace(f'channel00{segmentation_channel.value}', 'channel099') # save out labelled image imsave(fn, labels.astype(np.uint16), check_contrast=False)
_____no_output_____
BSD-3-Clause
stardist_segmentation.ipynb
quantumjot/segment-classify-track
Introduction to Language Processing Concepts Original tutorial by Brain Lehman, with updates by Fiona PigottThe goal of this tutorial is to introduce a few basical vocabularies, ideas, and Python libraries for thinking about topic modeling, in order to make sure that we have a good set of vocabulary to talk more in-depth about processing languge with Python later. We'll spend some time on defining vocabulary for topic modeling and using basic topic modeling tools.A big thank-you to the good people at the Stanford NLP group, for their informative and helpful online book: https://nlp.stanford.edu/IR-book/. Definitions.1. **Document**: a body of text (eg. tweet)2. **Tokenization**: dividing a document into pieces (and maybe throwing away some characters), in English this often (but not necessarily) means words separated by spaces and puctuation.3. **Text corpus**: the set of documents that contains the text for the analysis (eg. many tweets)4. **Stop words**: words that occur so frequently, or have so little topical meaning, that they are excluded (e.g., "and")5. **Vectorize**: Turn some documents into vectors6. **Vector corpus**: the set of documents transformed such that each token is a tuple (token_id , doc_freq)
# first, get some text: import fileinput try: import ujson as json except ImportError: import json documents = [] for line in fileinput.FileInput("example_tweets.json"): documents.append(json.loads(line)["text"])
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
1) DocumentIn the case of the text that we just imported, each entry in the list is a "document"--a single body of text, hopefully with some coherent meaning.
print("One document: \"{}\"".format(documents[0]))
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
2) TokenizationWe split each document into smaller pieces ("tokens") in a process called tokenization. Tokens can be counted, and most importantly, compared between documents. There are potentially many different ways to tokenize text--splitting on spaces, removing punctionation, diving the document into n-character pieces--anything that gives us tokens that we can, hopefully, effectively compare across documents and derive meaning from.Related to tokenization are processes called *stemming* and *lemmatiztion* which can help when using tokens to model topics based on the meaning of a word. In the phrases "they run" and "he runs" (space separated tokens: ["they", "run"] and ["he", "runs"]) the words "run" and "run*s*" mean basically the same thing, but are two different tokens. Stemming and/or lemmatization help us compare tokens with the same meaning but different spelling/suffixes. Lemmatization:Uses a dictionary of words and their possible morphologies to map many different forms of a base word ("lemma") to a single lemma, comparable across documents. E.g.: "run", "ran", "runs", and "running" might all map to the lemma "run" Stemming: Uses a set of heuristic rules to try to approximate lemmatization, without knowing the words in advance. For the English language, a simple and effective stemming algorithm might simply be to remove an "s" from the ends of words, or an "ing" from the end of words. E.g.: "run", "runs", and "running" all map to "run," but "ran" (an irregularrly conjugated verb) would not. Stemming is particularly interesting and applicable in social data, because while some words are decidely *not* standard English, conventinoal rules of grammar still apply. A fan of the popular singer Justin Bieber might call herself a "belieber," while a group of fans call themselves "beliebers." You won't find "belieber" in any English lemmatization dictionary, but a good stemming algorithm will still map "belieber" and "beliebers" to the same token ("belieber", or even "belieb", if we remover the common suffix "er").
from nltk.stem import porter from nltk.tokenize import TweetTokenizer # tokenize the documents # find good information on tokenization: # https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html # find documentation on pre-made tokenizers and options here: # http://www.nltk.org/api/nltk.tokenize.html tknzr = TweetTokenizer(reduce_len = True) # stem the documents # find good information on stemming and lemmatization: # https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html # find documentation on available pre-implemented stemmers here: # http://www.nltk.org/api/nltk.stem.html stemmer = porter.PorterStemmer() for doc in documents[0:10]: tokenized = tknzr.tokenize(doc) stemmed = [stemmer.stem(x) for x in tokenized] print("Original document:\n{}\nTokenized result:\n{}\nStemmed result:\n{}\n".format( doc, tokenized, stemmed))
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
3) Text corpusThe text corpus is a collection of all of the documents (Tweets) that we're interested in modeling. Topic modeling and/or clustering on a corpus tends to work best if that corpus has some similar themes--this will mean that some tokens overlap, and we can get signal out of when documents share (or do not share) tokens. Modeling text tends to get much harder the more different, uncommon and unrelated tokens appear in a text, especially when we are working with social data, where tokens don't necessarily appear in a dictionary. This difficultly (of having many, many unrelated tokens as dimension in our model) is one example of the [curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality).
# number of documents in the corpus print("There are {} documents in the corpus.".format(len(documents)))
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
4) Stop words:Stop words are simply tokens that we've chosen to remove from the corpus, for any reason. In English, removing words like "and", "the", "a", "at", and "it" are common choices for stop words. Stop words can also be edited per project requirement, in case some words are too common in a particular dataset to be meaningful (another way to do stop word removal is to simply remove any word that appears in more than some fixed percentage of documents).
from nltk.corpus import stopwords stopset = set(stopwords.words('english')) print("The English stop words list provided by NLTK: ") print(stopset) stopset.update(["twitter"]) # add token stopset.remove("i") # remove token print("\nAdd or remove stop words form the set: ") print(stopset)
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
5) Vectorize:Transform each document into a vector. There are several good choices that you can make about how to do this transformation, and I'll talk about each of them in a second.In order to vectorize documents in a corpus (without any dimensional reduction around the vocabulary), think of each document as a row in a matrix, and each column as a word in the vocabulary of the entire corpus. In order to vectorize a corpus, we must read the entire corpus, assign one word to each column, and then turn each document into a row.**Example**: **Documents**: "I love cake", "I hate chocolate", "I love chocolate cake", "I love cake, but I hate chocolate cake" **Stopwords**: Say, because the word "but" is a conjunction, we want to make it a stop word (not include it in our document vectors)**Vocabulary**: "I" (column 1), "love" (column 2), "cake" (column 3), "hate" (column 4), "chocolate" (column 5)\begin{equation*}\begin{matrix}\text{"I love cake" } & =\\\text{"I hate chocolate" } & =\\\text{"I love chocolate cake" } & = \\\text{"I love cake, but I hate chocolate cake"} & =\end{matrix}\qquad\begin{bmatrix}1 & 1 & 1 & 0 & 0\\1 & 0 & 0 & 1 & 1\\1 & 1 & 1 & 0 & 1\\2 & 1 & 2 & 1 & 1\end{bmatrix}\end{equation*}Vectorization like this don't take into account word order (we call this property "bag of words"), and in the above example I am simply counting the frequency of each term in each document.
# we're going to use the vectorizer functions that scikit learn provides # define the tokenizer that we want to use # must be a callable function that takes a document and returns a list of tokens tknzr = TweetTokenizer(reduce_len = True) stemmer = porter.PorterStemmer() def myTokenizer(doc): return [stemmer.stem(x) for x in tknzr.tokenize(doc)] # choose the stopword set that we want to use stopset = set(stopwords.words('english')) stopset.update(["http","https","twitter","amp"]) # vectorize # we're using the scikit learn CountVectorizer function, which is very handy # documentation here: # http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer vectorizer = CountVectorizer(tokenizer = myTokenizer, stop_words = stopset) vectorized_documents = vectorizer.fit_transform(documents) vectorized_documents import matplotlib.pyplot as plt %matplotlib inline _ = plt.hist(vectorized_documents.todense().sum(axis = 1)) _ = plt.title("Number of tokens per document") _ = plt.xlabel("Number of tokens") _ = plt.ylabel("Number of documents with x tokens") from numpy import logspace, ceil, histogram, array # get the token frequency token_freq = sorted(vectorized_documents.todense().astype(bool).sum(axis = 0).tolist()[0], reverse = False) # make a histogram with log scales bins = array([ceil(x) for x in logspace(0, 3, 5)]) widths = (bins[1:] - bins[:-1]) hist = histogram(token_freq, bins=bins) hist_norm = hist[0]/widths # plot (notice that most tokens only appear in one document) plt.bar(bins[:-1], hist_norm, widths) plt.xscale('log') plt.yscale('log') _ = plt.title("Number of documents in which each token appears") _ = plt.xlabel("Number of documents") _ = plt.ylabel("Number of tokens")
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
Bag of wordsTaking all the words from a document, and sticking them in a bag. Order does not matter, which could cause a problem. "Alice loves cake" might have a different meaning than "Cake loves Alice." FrequencyCounting the number of times a word appears in a document. Tf-Idf (term frequency inverse document frequency):A statistic that is intended to reflect how important a word is to a document in a collection or corpus. The Tf-Idf value increases proportionally to the number of times a word appears in the document and is inversely proportional to the frequency of the word in the corpus--this helps control words that are generally more common than others. There are several different possibilities for computing the tf-idf statistic--choosing whether to normalize the vectors, choosing whether to use counts or the logarithm of counts, etc. I'm going to show how scikit-learn computed the tf-idf statistic by default, with more information available in the documentation of the sckit-learn [TfidfVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html).$tf(t)$ : Term Frequency, count of the number of times each term appears in the document. $idf(d,t)$ : Inverse document frequency. $df(d,t)$ : Document frequency, the count of the number of documents in which the term appears. $$tfidf(t) = tf(t) * \log\big(\frac{1 + n}{1 + df(d, t)}\big) + 1$$We also then take the Euclidean ($l2$) norm of each document vector, so that long documents (documents with many non-stopword tokens) have the same norm as shorter documents.
# documentation on this sckit-learn function here: # http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html tfidf_vectorizer = TfidfVectorizer(tokenizer = myTokenizer, stop_words = stopset) tfidf_vectorized_documents = tfidf_vectorizer.fit_transform(documents) tfidf_vectorized_documents # you can look at two vectors for the same document, from 2 different vectorizers: tfidf_vectorized_documents[0].todense().tolist()[0] vectorized_documents[0].todense().tolist()[0]
_____no_output_____
Unlicense
language-processing-vocab/language_processing_vocab.ipynb
prakash123mayank/Data-Science-45min-Intros
[View in Colaboratory](https://colab.research.google.com/github/kartikeyab/Kaggle-Codes/blob/master/MovieReviews.ipynb)
from keras.preprocessing.text import Tokenizer tokenizer = Tokenizer(num_words = 10000) import pandas as pd import numpy as np from keras.utils import to_categorical from google.colab import files uploaded = files.upload() #loading data train_df = pd.read_csv('train.tsv', sep='\t', header=0) x_train = train_df['Phrase'].values y_train = train_df['Sentiment'].values x_train[1000] , y_train[1000] tokenizer.fit_on_texts(x_train) tokenizer.word_index x_train_tokens = tokenizer.texts_to_sequences(x_train) y_train = to_categorical(y_train) x_train[7] , y_train[7] num_token = [ len(x) for x in x_train] num_token = np.array(num_token) max_tokens = np.mean(num_token) + 2*np.std(num_token) print(max_tokens) from keras.preprocessing.sequence import pad_sequences x_train_pad = pad_sequences(x_train_tokens, maxlen = 116 , padding = 'pre') x_train_pad[1] from keras.models import Sequential from keras.layers import Embedding , Dense , Conv1D , MaxPooling1D , GRU, LSTM , Flatten , Dropout from keras.optimizers import adagrad num_classes = 5 model = Sequential() model.add(Embedding(input_dim = 10000, input_length = 116 ,output_dim = 128)) model.add(Conv1D(128 , kernel_size = 3 , activation = 'relu')) model.add(Conv1D(64 , kernel_size = 3 , activation = 'relu')) model.add(MaxPooling1D(pool_size =2)) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(250)) model.add(Dense(num_classes, activation = 'sigmoid')) model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy']) model.summary() model.fit(x_train_pad, y_train ,validation_split = 0.2, epochs = 10, batch_size = 256, shuffle = True)
_____no_output_____
MIT
MovieReviews.ipynb
kartikeyab/Kaggle-Codes
This is the first of three solutions to identify offensive language or hate speech in a set of user comments. The code is tested on actual data provided from a day's user comments. This solution utilizes a dictionary that stores all common offensive words and identifies them in any given review, which is then flagged for review. The dictionary is extracted from a Kaggle dataset of offensive tweets.*Note: This code is incapable of detecting sentence patterns that may predict hate speech.
! pip install nltk ! python -m textblob.download_corpora import nltk import csv import collections import pandas as pd from collections import Counter from nltk.corpus import stopwords # extracting offensive language from twitter kaggle data to final_list nltk.download('stopwords') raw_reviews = [] reviews_filename = '/content/drive/MyDrive/labeled_data.csv' with open(reviews_filename, 'r') as reviews_csvfile: csvreader = csv.reader(reviews_csvfile) next(csvreader) for i in range(1000): # 10399 row = next(csvreader) if int(row[3]) != 0: review = row[-1] review_arr = review.split(":") raw_reviews.append(review_arr[-1]) review_words = [] for review in raw_reviews: review_arr = review.split(" ") for review_word in review_arr: if "\"" not in review_word and review_word != "" and not "&" in review_word and review_word != "-" and review_word != "love" and "I" not in review_word and "'" not in review_word and review_word != "got": review_words.append(review_word) stop_words = set(stopwords.words('english')) with open('/content/drive/MyDrive/common_words.txt','r') as file: common_words = file.read() words_list = [word for word in review_words if not word in stop_words and not word in common_words] final_list = [] for word in Counter(words_list).most_common(9): final_list.append(word[0]) # adding reviews to formatted Data Frame raw_reviews = [] reviews_filename = '/content/drive/MyDrive/reviews.csv.txt' with open(reviews_filename, 'r') as reviews_csvfile: csvreader = csv.reader(reviews_csvfile) next(csvreader) next(csvreader) for i in range(10397): row = next(csvreader) if (len(row) >= 5): row.pop(0) row.pop(-1) row[2] = ''.join(row[2].split()) if row[2].replace('.', '', 1).isdigit(): row[2] = float(row[2]) row[1] = row[1].rstrip() if not row[1] == "" and isinstance(row[2], float): raw_reviews.append(row) table = pd.DataFrame(data = raw_reviews, columns = ['ID', 'Comments', 'Recommend']) table # Return flagged comments for human review. In # this case, the comments marked only contain # contain words that are made up of a word in the # dictionary. for col, row in table.iterrows(): curr_review = row['Comments'] for word in final_list: word = word + "." if word in curr_review: print("offensive lang") print(curr_review)
offensive lang She was very quick and informative. No bullshit. You could tell she had a smile even with her mask. Thanks!
Apache-2.0
solution_1.ipynb
saanaz379/user-comment-classifier
Neuromatch Academy: Week 1, Day 3, Tutorial 3 Model Fitting: Confidence intervals and bootstrapping**Content creators**: Pierre-Étienne Fiquet, Anqi Wu, Alex Hyafil with help from Byron Galbraith**Content reviewers**: Lina Teichmann, Saeed Salehi, Patrick Mineault, Ella Batty, Michael Waskom Tutorial ObjectivesThis is Tutorial 3 of a series on fitting models to data. We start with simple linear regression, using least squares optimization (Tutorial 1) and Maximum Likelihood Estimation (Tutorial 2). We will use bootstrapping to build confidence intervals around the inferred linear model parameters (Tutorial 3). We'll finish our exploration of regression models by generalizing to multiple linear regression and polynomial regression (Tutorial 4). We end by learning how to choose between these various models. We discuss the bias-variance trade-off (Tutorial 5) and Cross Validation for model selection (Tutorial 6).In this tutorial, we wil discuss how to gauge how good our estimated model parameters are. - Learn how to use bootstrapping to generate new sample datasets- Estimate our model parameter on these new sample datasets- Quantify the variance of our estimate using confidence intervals
#@title Video 1: Confidence Intervals & Bootstrapping from IPython.display import YouTubeVideo video = YouTubeVideo(id="hs6bVGQNSIs", width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
Up to this point we have been finding ways to estimate model parameters to fit some observed data. Our approach has been to optimize some criterion, either minimize the mean squared error or maximize the likelihood while using the entire dataset. How good is our estimate really? How confident are we that it will generalize to describe new data we haven't seen yet?One solution to this is to just collect more data and check the MSE on this new dataset with the previously estimated parameters. However this is not always feasible and still leaves open the question of how quantifiably confident we are in the accuracy of our model.In Section 1, we will explore how to implement bootstrapping. In Section 2, we will build confidence intervals of our estimates using the bootstrapping method. --- Setup
import numpy as np import matplotlib.pyplot as plt #@title Figure Settings %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") #@title Helper Functions def solve_normal_eqn(x, y): """Solve the normal equations to produce the value of theta_hat that minimizes MSE. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. thata_hat (float): An estimate of the slope parameter. Returns: float: the value for theta_hat arrived from minimizing MSE """ theta_hat = (x.T @ y) / (x.T @ x) return theta_hat
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
--- Section 1: Bootstrapping[Bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)) is a widely applicable method to assess confidence/uncertainty about estimated parameters, it was originally [proposed](https://projecteuclid.org/euclid.aos/1176344552) by [Bradley Efron](https://en.wikipedia.org/wiki/Bradley_Efron). The idea is to generate many new synthetic datasets from the initial true dataset by randomly sampling from it, then finding estimators for each one of these new datasets, and finally looking at the distribution of all these estimators to quantify our confidence.Note that each new resampled datasets will be the same size as our original one, with the new data points sampled with replacement i.e. we can repeat the same data point multiple times. Also note that in practice we need a lot of resampled datasets, here we use 2000.To explore this idea, we will start again with our noisy samples along the line $y_n = 1.2x_n + \epsilon_n$, but this time only use half the data points as last time (15 instead of 30).
#@title #@markdown Execute this cell to simulate some data # setting a fixed seed to our random number generator ensures we will always # get the same psuedorandom number sequence np.random.seed(121) # Let's set some parameters theta = 1.2 n_samples = 15 # Draw x and then calculate y x = 10 * np.random.rand(n_samples) # sample from a uniform distribution over [0,10) noise = np.random.randn(n_samples) # sample from a standard normal distribution y = theta * x + noise fig, ax = plt.subplots() ax.scatter(x, y) # produces a scatter plot ax.set(xlabel='x', ylabel='y');
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
Exercise 1: Resample Dataset with ReplacementIn this exercise you will implement a method to resample a dataset with replacement. The method accepts $x$ and $y$ arrays. It should return a new set of $x'$ and $y'$ arrays that are created by randomly sampling from the originals.We will then compare the original dataset to a resampled dataset.TIP: The [numpy.random.choice](https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html) method would be useful here.
def resample_with_replacement(x, y): """Resample data points with replacement from the dataset of `x` inputs and `y` measurements. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. Returns: ndarray, ndarray: The newly resampled `x` and `y` data points. """ ####################################################### ## TODO for students: resample dataset with replacement # Fill out function and remove raise NotImplementedError("Student exercise: resample dataset with replacement") ####################################################### # Get array of indices for resampled points sample_idx = ... # Sample from x and y according to sample_idx x_ = ... y_ = ... return x_, y_ fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5)) ax1.scatter(x, y) ax1.set(title='Original', xlabel='x', ylabel='y') # Uncomment below to test your function #x_, y_ = resample_with_replacement(x, y) #ax2.scatter(x_, y_, color='c') ax2.set(title='Resampled', xlabel='x', ylabel='y', xlim=ax1.get_xlim(), ylim=ax1.get_ylim()); # to_remove solution def resample_with_replacement(x, y): """Resample data points with replacement from the dataset of `x` inputs and `y` measurements. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. Returns: ndarray, ndarray: The newly resampled `x` and `y` data points. """ # Get array of indices for resampled points sample_idx = np.random.choice(len(x), size=len(x), replace=True) # Sample from x and y according to sample_idx x_ = x[sample_idx] y_ = y[sample_idx] return x_, y_ with plt.xkcd(): fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5)) ax1.scatter(x, y) ax1.set(title='Original', xlabel='x', ylabel='y') x_, y_ = resample_with_replacement(x, y) ax2.scatter(x_, y_, color='c') ax2.set(title='Resampled', xlabel='x', ylabel='y', xlim=ax1.get_xlim(), ylim=ax1.get_ylim());
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
In the resampled plot on the right, the actual number of points is the same, but some have been repeated so they only display once.Now that we have a way to resample the data, we can use that in the full bootstrapping process. Exercise 2: Bootstrap EstimatesIn this exercise you will implement a method to run the bootstrap process of generating a set of $\hat\theta$ values from a dataset of $x$ inputs and $y$ measurements. You should use `resample_with_replacement` here, and you may also invoke helper function `solve_normal_eqn` from Tutorial 1 to produce the MSE-based estimator.We will then use this function to look at the theta_hat from different samples.
def bootstrap_estimates(x, y, n=2000): """Generate a set of theta_hat estimates using the bootstrap method. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. n (int): The number of estimates to compute Returns: ndarray: An array of estimated parameters with size (n,) """ theta_hats = np.zeros(n) ############################################################################## ## TODO for students: implement bootstrap estimation # Fill out function and remove raise NotImplementedError("Student exercise: implement bootstrap estimation") ############################################################################## # Loop over number of estimates for i in range(n): # Resample x and y x_, y_ = ... # Compute theta_hat for this sample theta_hats[i] = ... return theta_hats np.random.seed(123) # set random seed for checking solutions # Uncomment below to test function # theta_hats = bootstrap_estimates(x, y, n=2000) # print(theta_hats[0:5]) # to_remove solution def bootstrap_estimates(x, y, n=2000): """Generate a set of theta_hat estimates using the bootstrap method. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. n (int): The number of estimates to compute Returns: ndarray: An array of estimated parameters with size (n,) """ theta_hats = np.zeros(n) # Loop over number of estimates for i in range(n): # Resample x and y x_, y_ = resample_with_replacement(x, y) # Compute theta_hat for this sample theta_hats[i] = solve_normal_eqn(x_, y_) return theta_hats np.random.seed(123) # set random seed for checking solutions theta_hats = bootstrap_estimates(x, y, n=2000) print(theta_hats[0:5])
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
You should see `[1.27550888 1.17317819 1.18198819 1.25329255 1.20714664]` as the first five estimates. Now that we have our bootstrap estimates, we can visualize all the potential models (models computed with different resampling) together to see how distributed they are.
#@title #@markdown Execute this cell to visualize all potential models fig, ax = plt.subplots() # For each theta_hat, plot model theta_hats = bootstrap_estimates(x, y, n=2000) for i, theta_hat in enumerate(theta_hats): y_hat = theta_hat * x ax.plot(x, y_hat, c='r', alpha=0.01, label='Resampled Fits' if i==0 else '') # Plot observed data ax.scatter(x, y, label='Observed') # Plot true fit data y_true = theta * x ax.plot(x, y_true, 'g', linewidth=2, label='True Model') ax.set( title='Bootstrapped Slope Estimation', xlabel='x', ylabel='y' ) # Change legend line alpha property handles, labels = ax.get_legend_handles_labels() handles[0].set_alpha(1) ax.legend();
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
This looks pretty good! The bootstrapped estimates spread around the true model, as we would have hoped. Note that here we have the luxury to know the ground truth value for $\theta$, but in applications we are trying to guess it from data. Therefore, assessing the quality of estimates based on finite data is a task of fundamental importance in data analysis. --- Section 2: Confidence IntervalsLet us now quantify how uncertain our estimated slope is. We do so by computing [confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) (CIs) from our bootstrapped estimates. The most direct approach is to compute percentiles from the empirical distribution of bootstrapped estimates. Note that this is widely applicable as we are not assuming that this empirical distribution is Gaussian.
#@title #@markdown Execute this cell to plot bootstrapped CI theta_hats = bootstrap_estimates(x, y, n=2000) print(f"mean = {np.mean(theta_hats):.2f}, std = {np.std(theta_hats):.2f}") fig, ax = plt.subplots() ax.hist(theta_hats, bins=20, facecolor='C1', alpha=0.75) ax.axvline(theta, c='g', label=r'True $\theta$') ax.axvline(np.percentile(theta_hats, 50), color='r', label='Median') ax.axvline(np.percentile(theta_hats, 2.5), color='b', label='95% CI') ax.axvline(np.percentile(theta_hats, 97.5), color='b') ax.legend() ax.set( title='Bootstrapped Confidence Interval', xlabel=r'$\hat{{\theta}}$', ylabel='count', xlim=[1.0, 1.5] );
_____no_output_____
CC-BY-4.0
tutorials/W1D3_ModelFitting/W1D3_Tutorial3.ipynb
DianaMosquera/course-content
Dependencies
import warnings, math, json, glob import pandas as pd import tensorflow.keras.layers as L import tensorflow.keras.backend as K from tensorflow.keras import Model from transformers import TFAutoModelForSequenceClassification, TFAutoModel, AutoTokenizer from commonlit_scripts import * seed = 0 seed_everything(seed) warnings.filterwarnings('ignore') pd.set_option('display.max_colwidth', 150)
_____no_output_____
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Hardware configuration
strategy, tpu = get_strategy() AUTO = tf.data.AUTOTUNE REPLICAS = strategy.num_replicas_in_sync print(f'REPLICAS: {REPLICAS}')
REPLICAS: 1
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Load data
base_path = '/kaggle/input/' test_filepath = base_path + 'commonlitreadabilityprize/test.csv' test = pd.read_csv(test_filepath) print(f'Test samples: {len(test)}') display(test.head())
Test samples: 7
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Model parameters
input_noteboks = [x for x in os.listdir(base_path) if '-commonlit-' in x] input_base_path = f'{base_path}{input_noteboks[0]}/' with open(input_base_path + 'config.json') as json_file: config = json.load(json_file) config
_____no_output_____
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Auxiliary functions
# Datasets utility functions def custom_standardization(text, is_lower=True): if is_lower: text = text.lower() # if encoder is uncased text = text.strip() return text def sample_target(features, target): mean, stddev = target sampled_target = tf.random.normal([], mean=tf.cast(mean, dtype=tf.float32), stddev=tf.cast(stddev, dtype=tf.float32), dtype=tf.float32) return (features, sampled_target) def get_dataset(pandas_df, tokenizer, labeled=True, ordered=False, repeated=False, is_sampled=False, batch_size=32, seq_len=128, is_lower=True): """ Return a Tensorflow dataset ready for training or inference. """ text = [custom_standardization(text, is_lower) for text in pandas_df['excerpt']] # Tokenize inputs tokenized_inputs = tokenizer(text, max_length=seq_len, truncation=True, padding='max_length', return_tensors='tf') if labeled: dataset = tf.data.Dataset.from_tensor_slices(({'input_ids': tokenized_inputs['input_ids'], 'attention_mask': tokenized_inputs['attention_mask']}, (pandas_df['target'], pandas_df['standard_error']))) if is_sampled: dataset = dataset.map(sample_target, num_parallel_calls=tf.data.AUTOTUNE) else: dataset = tf.data.Dataset.from_tensor_slices({'input_ids': tokenized_inputs['input_ids'], 'attention_mask': tokenized_inputs['attention_mask']}) if repeated: dataset = dataset.repeat() if not ordered: dataset = dataset.shuffle(2048) dataset = dataset.batch(batch_size) dataset = dataset.cache() dataset = dataset.prefetch(tf.data.AUTOTUNE) return dataset model_path_list = glob.glob(f'{input_base_path}*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep='\n')
Models to predict: /kaggle/input/39-commonlit-roberta-base-target-sampling-exp/model_0.h5
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Model
def model_fn(encoder, seq_len=256): input_ids = L.Input(shape=(seq_len,), dtype=tf.int32, name='input_ids') input_attention_mask = L.Input(shape=(seq_len,), dtype=tf.int32, name='attention_mask') outputs = encoder({'input_ids': input_ids, 'attention_mask': input_attention_mask}) last_hidden_state = outputs['last_hidden_state'] cls_token = last_hidden_state[:, 0, :] output = L.Dense(1, name='output')(cls_token) model = Model(inputs=[input_ids, input_attention_mask], outputs=[output]) return model with strategy.scope(): encoder = TFAutoModel.from_pretrained(config['BASE_MODEL']) # Freeze embeddings encoder.layers[0].embeddings.trainable = False model = model_fn(encoder, config['SEQ_LEN']) model.summary()
Some layers from the model checkpoint at /kaggle/input/huggingface-roberta/roberta-base/ were not used when initializing TFRobertaModel: ['lm_head'] - This IS expected if you are initializing TFRobertaModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model). - This IS NOT expected if you are initializing TFRobertaModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). All the layers of TFRobertaModel were initialized from the model checkpoint at /kaggle/input/huggingface-roberta/roberta-base/. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFRobertaModel for predictions without further training.
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Test set predictions
tokenizer = AutoTokenizer.from_pretrained(config['BASE_MODEL']) test_pred = [] for model_path in model_path_list: print(model_path) if tpu: tf.tpu.experimental.initialize_tpu_system(tpu) K.clear_session() model.load_weights(model_path) # Test predictions test_ds = get_dataset(test, tokenizer, labeled=False, ordered=True, batch_size=config['BATCH_SIZE'], seq_len=config['SEQ_LEN']) x_test = test_ds.map(lambda sample: sample) test_pred.append(model.predict(x_test))
/kaggle/input/39-commonlit-roberta-base-target-sampling-exp/model_0.h5
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
Test set predictions
submission = test[['id']] submission['target'] = np.mean(test_pred, axis=0) submission.to_csv('submission.csv', index=False) display(submission.head(10))
_____no_output_____
MIT
Model backlog/Inference/39-commonlit-inf-roberta-base-target-sampling-exp.ipynb
dimitreOliveira/CommonLit-Readability-Prize
NASA Mars News
mars={} url = 'https://mars.nasa.gov/news/' browser.visit(url) html = browser.html soup = BeautifulSoup(html,'html.parser') resultNasaMars = soup.findAll("div",class_="content_title") nasaTitle = resultNasaMars[1].a.text result = soup.find("div" ,class_="article_teaser_body") nasaPara = result.text mars["news_title"] = nasaTitle mars["news_p"] = nasaPara mars
_____no_output_____
ADSL
Missions_to_Mars/mission_to_mars.ipynb
XxTopShottaxX/Web-Scraping-challenge
JPL Mars Space Images
url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' browser.visit(url) browser.find_by_id("full_image").click() browser.find_link_by_partial_text("more info").click() html = browser.html soup = BeautifulSoup(html,'html.parser') resultJPLimage = soup.find("figure",class_="lede") resultJPLimage.a.img["src"] imgJPL = 'https://www.jpl.nasa.gov/' + resultJPLimage.a.img["src"] mars['featured_image_url'] = imgJPL mars
_____no_output_____
ADSL
Missions_to_Mars/mission_to_mars.ipynb
XxTopShottaxX/Web-Scraping-challenge
Mars Facts
mars_df = pd.read_html('https://space-facts.com/mars/')[0] mars_df.columns = ["Description","Value"] mars_df.set_index("Description", inplace = True) mars["facts"] = mars_df.to_html() mars
_____no_output_____
ADSL
Missions_to_Mars/mission_to_mars.ipynb
XxTopShottaxX/Web-Scraping-challenge
Load raw data
import numpy as np data = np.loadtxt('SlowSteps1.csv', delimiter = ',') # load the raw data, change the filename as required!
_____no_output_____
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Find spikes
time_s = (data[:,8]-data[0,8])/1000000 # set the timing array to seconds and subtract 1st entry to zero it n_spikes = 0 spike_times = [] # in seconds spike_points = [] # in timepoints for x in range(1, data.shape[0]-1): if (data[x,0]>10 and data[x-1,0]<10): # looks for all instances where subsequent Vm points jump from <10 to >10 spike_times.append(time_s[x]) spike_points.append(x) n_spikes+=1 print(n_spikes, "spikes detected")
168 spikes detected
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Compute spike rate
spike_rate = np.zeros(data.shape[0]) for x in range(0, n_spikes-1): current_rate = 1/(spike_times[x+1]-spike_times[x]) spike_rate[spike_points[x]:spike_points[x+1]]=current_rate
_____no_output_____
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Plot raw data and spike rate
from bokeh.plotting import figure, output_file, show from bokeh.layouts import column from bokeh.models import Range1d output_file("RawDataPlot.html") spike_plot = figure(plot_width=1200, plot_height = 100) spike_plot.line(time_s[:],spike_rate[:], line_width=1, line_color="black") # Spike rate spike_plot.yaxis[0].axis_label = 'Rate (Hz)' spike_plot.xgrid.grid_line_color =None spike_plot.ygrid.grid_line_color =None spike_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels spike_plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks vm_plot = figure(plot_width=1200, plot_height = 300, y_range=Range1d(-100, 50),x_range=spike_plot.x_range) vm_plot.line(time_s[:],data[:,0], line_width=1, line_color="black") # Vm vm_plot.scatter(spike_times[:],45, line_color="black") # Rasterplot over spikes vm_plot.yaxis[0].axis_label = 'Vm (mV)' vm_plot.xgrid.grid_line_color =None vm_plot.ygrid.grid_line_color =None vm_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels itotal_plot = figure(plot_width=1200, plot_height = 200, x_range=spike_plot.x_range) itotal_plot.line(time_s[:], data[:,1], line_width=1, line_color="black") # Itotal itotal_plot.yaxis[0].axis_label = 'I total (a.u.)' itotal_plot.xgrid.grid_line_color =None itotal_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels in_spikes_plot = figure(plot_width=1200, plot_height = 80, y_range=Range1d(-0.1,1.1), x_range=spike_plot.x_range) in_spikes_plot.line(time_s[:], data[:,3], line_width=1, line_color="black") # Spikes in from Port 1 in_spikes_plot.line(time_s[:], data[:,4], line_width=1, line_color="grey") # Spikes in from Port 2 in_spikes_plot.yaxis[0].axis_label = 'Input spikes' in_spikes_plot.xgrid.grid_line_color =None in_spikes_plot.ygrid.grid_line_color =None in_spikes_plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks in_spikes_plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks in_spikes_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels in_spikes_plot.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels stim_plot = figure(plot_width=1200, plot_height = 100,y_range=Range1d(-0.1,1.1), x_range=spike_plot.x_range) stim_plot.line(time_s[:], data[:,2], line_width=1, line_color="black") # Stimulus stim_plot.yaxis[0].axis_label = 'Stimulus' stim_plot.xaxis[0].axis_label = 'Time (s)' stim_plot.xgrid.grid_line_color =None stim_plot.ygrid.grid_line_color =None stim_plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks stim_plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks stim_plot.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels show(column(spike_plot,vm_plot,itotal_plot,in_spikes_plot,stim_plot))
WARNING:bokeh.core.validation.check:W-1004 (BOTH_CHILD_AND_ROOT): Models should not be a document root if they are in a layout box: Figure(id='25e4d8ca-bc35-44d5-9572-f71aea70c895', ...)
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Analysis Option 1: Trigger stimuli and align
stimulus_times = [] stimulus_times_s = [] for x in range(0, data.shape[0]-1): # goes through each timepoint if (data[x,2]<data[x+1,2]): # checks if the stimulus went from 0 to 1 stimulus_times.append(x) ## make a list of times (in points) when stimulus increased stimulus_times_s.append(time_s[x]) ## also make a list of times (in seconds) loop_duration = stimulus_times[1]-stimulus_times[0] # compute arraylength for single stimulus loop_duration_s = stimulus_times_s[1]-stimulus_times_s[0] # compute arraylength for single stimulus also in s print(loop_duration, "points per loop;", loop_duration_s, "seconds") sr_loops = [] vm_loops = [] itotal_loops = [] stim_loops = [] stimulus_times = np.where(data[:,2]>np.roll(data[:,2], axis = 0, shift = 1)) ## make a list of times when stimulus increased (again) sr_loops = np.vstack([spike_rate[x:x+loop_duration] for x in stimulus_times[0][:-1]]) vm_loops = np.vstack([data[x:x+loop_duration, 0] for x in stimulus_times[0][:-1]]) itotal_loops = np.vstack([data[x:x+loop_duration, 1] for x in stimulus_times[0][:-1]]) stim_loops = np.vstack([data[x:x+loop_duration, 2] for x in stimulus_times[0][:-1]]) st_loops = [] for i, x in enumerate(stimulus_times[0][:-1]): st_loops.append([time_s[sp]-time_s[x] for sp in spike_points if sp > x and sp < x+loop_duration]) loops = vm_loops.shape[0] print(loops, "loops")
4000 points per loop; 7.27066 seconds 8 loops
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Make average arrays
sr_mean = np.mean(sr_loops, axis=0) vm_mean = np.mean(vm_loops, axis=0) itotal_mean = np.mean(itotal_loops, axis=0) stim_mean = np.mean(stim_loops, axis=0)
_____no_output_____
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Plot stimulus aligned data
from bokeh.plotting import figure, output_file, show from bokeh.layouts import column from bokeh.models import Range1d output_file("AlignedDataPlot.html") spike_plot = figure(plot_width=400, plot_height = 100) for i in range(0,loops-1): spike_plot.line(time_s[0:loop_duration],sr_loops[i,:], line_width=1, line_color="gray") # Vm individual repeats spike_plot.line(time_s[0:loop_duration],sr_mean[:], line_width=1.5, line_color="black") # Vm mean spike_plot.yaxis[0].axis_label = 'Rate (Hz)' spike_plot.xgrid.grid_line_color =None spike_plot.ygrid.grid_line_color =None spike_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels dot_plot = figure(plot_width=400, plot_height = 100, x_range=spike_plot.x_range) for i in range(0,loops-1): dot_plot.scatter(st_loops[i],i, line_color="black") # Rasterplot dot_plot.yaxis[0].axis_label = 'Repeat' dot_plot.xgrid.grid_line_color =None dot_plot.ygrid.grid_line_color =None dot_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels vm_plot = figure(plot_width=400, plot_height = 300, y_range=Range1d(-100, 40),x_range=spike_plot.x_range) for i in range(0,loops-1): vm_plot.line(time_s[0:loop_duration],vm_loops[i,:], line_width=1, line_color="gray") # Vm individual repeats vm_plot.line(time_s[0:loop_duration],vm_mean[:], line_width=1.5, line_color="black") # Vm mean vm_plot.yaxis[0].axis_label = 'Vm (mV)' vm_plot.xgrid.grid_line_color =None vm_plot.ygrid.grid_line_color =None vm_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels itotal_plot = figure(plot_width=400, plot_height = 200, x_range=spike_plot.x_range) for i in range(0,loops-1): itotal_plot.line(time_s[0:loop_duration], itotal_loops[i,:], line_width=1, line_color="gray") # Itotal individual repeats itotal_plot.line(time_s[0:loop_duration], itotal_mean[:], line_width=1.5, line_color="black") # Itotal mean itotal_plot.yaxis[0].axis_label = 'Itotal (a.u.)' itotal_plot.xgrid.grid_line_color =None itotal_plot.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels stim_plot = figure(plot_width=400, plot_height = 100,y_range=Range1d(-0.1,1.1), x_range=spike_plot.x_range) for i in range(0,loops-1): stim_plot.line(time_s[0:loop_duration], stim_loops[i,:], line_width=1, line_color="gray") # Stimulus individual repeats stim_plot.line(time_s[0:loop_duration], stim_mean[:], line_width=1.5, line_color="black") # Stimulus mean stim_plot.yaxis[0].axis_label = 'Stimulus' stim_plot.xaxis[0].axis_label = 'Time (s)' stim_plot.xgrid.grid_line_color =None stim_plot.ygrid.grid_line_color =None stim_plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks stim_plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks stim_plot.yaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels show(column(spike_plot,dot_plot,vm_plot,itotal_plot,stim_plot))
WARNING:bokeh.core.validation.check:W-1004 (BOTH_CHILD_AND_ROOT): Models should not be a document root if they are in a layout box: Figure(id='25e4d8ca-bc35-44d5-9572-f71aea70c895', ...)
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Analysis option 2: Spike triggered average (STA)
sta_points = 200 # number of points computed sta_individual = [] sta_individual = np.vstack([data[x-sta_points:x,2] for x in spike_points[2:-1]]) sta = np.mean(sta_individual, axis=0) import matplotlib.pyplot as plt plt.plot(time_s[0:200],sta[:]) plt.ylabel('Kernel amplitude') plt.xlabel('Time before spike (s)') plt.show()
_____no_output_____
MIT
Python Script/Spikeling Analysis.ipynb
hoijui/Spikeling
Convolutional Neural Networks: Step by StepWelcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. By the end of this notebook, you'll be able to: * Explain the convolution operation* Apply two different types of pooling operation* Identify the components used in a convolutional neural network (padding, stride, filter, ...) and their purpose* Build a convolutional neural network **Notation**:- Superscript $[l]$ denotes an object of the $l^{th}$ layer. - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.- Superscript $(i)$ denotes an object from the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example input. - Subscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer. - $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$. - $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$. You should be familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started! Table of Contents- [1 - Packages](1)- [2 - Outline of the Assignment](2)- [3 - Convolutional Neural Networks](3) - [3.1 - Zero-Padding](3-1) - [Exercise 1 - zero_pad](ex-1) - [3.2 - Single Step of Convolution](3-2) - [Exercise 2 - conv_single_step](ex-2) - [3.3 - Convolutional Neural Networks - Forward Pass](3-3) - [Exercise 3 - conv_forward](ex-3)- [4 - Pooling Layer](4) - [4.1 - Forward Pooling](4-1) - [Exercise 4 - pool_forward](ex-4)- [5 - Backpropagation in Convolutional Neural Networks (OPTIONAL / UNGRADED)](5) - [5.1 - Convolutional Layer Backward Pass](5-1) - [5.1.1 - Computing dA](5-1-1) - [5.1.2 - Computing dW](5-1-2) - [5.1.3 - Computing db](5-1-3) - [Exercise 5 - conv_backward](ex-5) - [5.2 Pooling Layer - Backward Pass](5-2) - [5.2.1 Max Pooling - Backward Pass](5-2-1) - [Exercise 6 - create_mask_from_window](ex-6) - [5.2.2 - Average Pooling - Backward Pass](5-2-2) - [Exercise 7 - distribute_value](ex-7) - [5.2.3 Putting it Together: Pooling Backward](5-2-3) - [Exercise 8 - pool_backward](ex-8) 1 - PackagesLet's first import all the packages that you will need during this assignment. - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.- np.random.seed(1) is used to keep all the random function calls consistent. This helps to grade your work.
import numpy as np import h5py import matplotlib.pyplot as plt from public_tests import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1)
_____no_output_____
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
2 - Outline of the AssignmentYou will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions to walk you through the steps:- Convolution functions, including: - Zero Padding - Convolve window - Convolution forward - Convolution backward (optional)- Pooling functions, including: - Pooling forward - Create mask - Distribute value - Pooling backward (optional) This notebook will ask you to implement these functions from scratch in `numpy`. In the next notebook, you will use the TensorFlow equivalents of these functions to build the following model:**Note**: For every forward function, there is a corresponding backward equivalent. Hence, at every step of your forward module you will store some parameters in a cache. These parameters are used to compute gradients during backpropagation. 3 - Convolutional Neural NetworksAlthough programming frameworks make convolutions easy to use, they remain one of the hardest concepts to understand in Deep Learning. A convolution layer transforms an input volume into an output volume of different size, as shown below. In this part, you will build every step of the convolution layer. You will first implement two helper functions: one for zero padding and the other for computing the convolution function itself. 3.1 - Zero-PaddingZero-padding adds zeros around the border of an image: Figure 1 : Zero-Padding Image (3 channels, RGB) with a padding of 2. The main benefits of padding are:- It allows you to use a CONV layer without necessarily shrinking the height and width of the volumes. This is important for building deeper networks, since otherwise the height/width would shrink as you go to deeper layers. An important special case is the "same" convolution, in which the height/width is exactly preserved after one layer. - It helps us keep more of the information at the border of an image. Without padding, very few values at the next layer would be affected by pixels at the edges of an image. Exercise 1 - zero_padImplement the following function, which pads all the images of a batch of examples X with zeros. [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html). Note if you want to pad the array "a" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do:```pythona = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), mode='constant', constant_values = (0,0))```
# GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- integer, amount of padding around each image on vertical and horizontal dimensions Returns: X_pad -- padded image of shape (m, n_H + 2 * pad, n_W + 2 * pad, n_C) """ #(≈ 1 line) # X_pad = None # YOUR CODE STARTS HERE X_pad = np.pad(X, ((0, 0), (pad, pad), (pad, pad), (0, 0)), mode='constant', constant_values = 0) # YOUR CODE ENDS HERE return X_pad np.random.seed(1) x = np.random.randn(4, 3, 3, 2) x_pad = zero_pad(x, 3) print ("x.shape =\n", x.shape) print ("x_pad.shape =\n", x_pad.shape) print ("x[1,1] =\n", x[1, 1]) print ("x_pad[1,1] =\n", x_pad[1, 1]) fig, axarr = plt.subplots(1, 2) axarr[0].set_title('x') axarr[0].imshow(x[0, :, :, 0]) axarr[1].set_title('x_pad') axarr[1].imshow(x_pad[0, :, :, 0]) zero_pad_test(zero_pad)
x.shape = (4, 3, 3, 2) x_pad.shape = (4, 9, 9, 2) x[1,1] = [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] x_pad[1,1] = [[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]] x.shape = (4, 3, 3, 2) x_pad.shape = (4, 9, 9, 2) x[1,1] = [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] x_pad[1,1] = [[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0.]] All tests passed!
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
3.2 - Single Step of Convolution In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: - Takes an input volume - Applies a filter at every position of the input- Outputs another volume (usually of different size) Figure 2 : Convolution operation with a filter of 3x3 and a stride of 1 (stride = amount you move the window each time you slide) In a computer vision application, each value in the matrix on the left corresponds to a single pixel value. You convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up and adding a bias. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output. Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation. Exercise 2 - conv_single_stepImplement `conv_single_step()`. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html). **Note**: The variable b will be passed in as a numpy array. If you add a scalar (a float or integer) to a numpy array, the result is a numpy array. In the special case of a numpy array containing a single value, you can cast it as a float to convert it to a scalar.
# GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev) b -- Bias parameters contained in a window - matrix of shape (1, 1, 1) Returns: Z -- a scalar value, the result of convolving the sliding window (W, b) on a slice x of the input data """ #(≈ 3 lines of code) # Element-wise product between a_slice_prev and W. Do not add the bias yet. # s = None # Sum over all entries of the volume s. # Z = None # Add bias b to Z. Cast b to a float() so that Z results in a scalar value. # Z = None # YOUR CODE STARTS HERE s = np.multiply(a_slice_prev, W) Z = np.sum(s) Z = Z + float(b) # YOUR CODE ENDS HERE return Z np.random.seed(1) a_slice_prev = np.random.randn(4, 4, 3) W = np.random.randn(4, 4, 3) b = np.random.randn(1, 1, 1) Z = conv_single_step(a_slice_prev, W, b) print("Z =", Z) conv_single_step_test(conv_single_step) assert (type(Z) == np.float64 or type(Z) == np.float32), "You must cast the output to float" assert np.isclose(Z, -6.999089450680221), "Wrong value"
Z = -6.999089450680221 All tests passed!
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
3.3 - Convolutional Neural Networks - Forward PassIn the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume: Exercise 3 - conv_forwardImplement the function below to convolve the filters `W` on an input activation `A_prev`. This function takes the following inputs:* `A_prev`, the activations output by the previous layer (for a batch of m inputs); * Weights are denoted by `W`. The filter window size is `f` by `f`.* The bias vector is `b`, where each filter has its own (single) bias. You also have access to the hyperparameters dictionary, which contains the stride and the padding. **Hint**: 1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do:```pythona_slice_prev = a_prev[0:2,0:2,:]```Notice how this gives a 3D slice that has height 2, width 2, and depth 3. Depth is the number of channels. This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define.2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find out how each of the corners can be defined using h, w, f and s in the code below. Figure 3 : Definition of a slice using vertical and horizontal start/end (with a 2x2 filter) This figure shows only a single channel. **Reminder**: The formulas relating the output shape of the convolution to the input shape are: $$n_H = \Bigl\lfloor \frac{n_{H_{prev}} - f + 2 \times pad}{stride} \Bigr\rfloor +1$$$$n_W = \Bigl\lfloor \frac{n_{W_{prev}} - f + 2 \times pad}{stride} \Bigr\rfloor +1$$$$n_C = \text{number of filters used in the convolution}$$ For this exercise, don't worry about vectorization! Just implement everything with for-loops. Additional Hints (if you're stuck):* Use array slicing (e.g.`varname[0:1,:,3:5]`) for the following variables: `a_prev_pad` ,`W`, `b` - Copy the starter code of the function and run it outside of the defined function, in separate cells. - Check that the subset of each array is the size and dimension that you're expecting. * To decide how to get the `vert_start`, `vert_end`, `horiz_start`, `horiz_end`, remember that these are indices of the previous layer. - Draw an example of a previous padded layer (8 x 8, for instance), and the current (output layer) (2 x 2, for instance). - The output layer's indices are denoted by `h` and `w`. * Make sure that `a_slice_prev` has a height, width and depth.* Remember that `a_prev_pad` is a subset of `A_prev_pad`. - Think about which one should be used within the for loops.
# GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): """ Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy array of shape (f, f, n_C_prev, n_C) b -- Biases, numpy array of shape (1, 1, 1, n_C) hparameters -- python dictionary containing "stride" and "pad" Returns: Z -- conv output, numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward() function """ # Retrieve dimensions from A_prev's shape (≈1 line) # (m, n_H_prev, n_W_prev, n_C_prev) = None # Retrieve dimensions from W's shape (≈1 line) # (f, f, n_C_prev, n_C) = None # Retrieve information from "hparameters" (≈2 lines) # stride = None # pad = None # Compute the dimensions of the CONV output volume using the formula given above. # Hint: use int() to apply the 'floor' operation. (≈2 lines) # n_H = None # n_W = None # Initialize the output volume Z with zeros. (≈1 line) # Z = None # Create A_prev_pad by padding A_prev # A_prev_pad = None # for i in range(None): # loop over the batch of training examples # a_prev_pad = None # Select ith training example's padded activation # for h in range(None): # loop over vertical axis of the output volume # Find the vertical start and end of the current "slice" (≈2 lines) # vert_start = None # vert_end = None # for w in range(None): # loop over horizontal axis of the output volume # Find the horizontal start and end of the current "slice" (≈2 lines) # horiz_start = None # horiz_end = None # for c in range(None): # loop over channels (= #filters) of the output volume # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line) # a_slice_prev = None # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈3 line) # weights = None # biases = None # Z[i, h, w, c] = None # YOUR CODE STARTS HERE (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape (f, f, n_C_prev, n_C) = W.shape stride = hparameters["stride"] pad = hparameters["pad"] n_H = int((n_H_prev - f + 2 * pad)/stride) + 1 n_W = int((n_W_prev - f + 2 * pad)/stride) + 1 Z = np.zeros((m, n_H, n_W, n_C)) A_prev_pad = zero_pad(A_prev, pad) for i in range(m): a_prev_pad = A_prev_pad[i,:,:,:] for h in range(n_H): vert_start = h*stride vert_end = vert_start + f for w in range(n_W): horiz_start = w*stride horiz_end = horiz_start + f for c in range(n_C): a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] weights = W[:,:,:,c] biases = b[:,:,:,c] Z[i, h, w, c] = conv_single_step(a_slice_prev, weights, biases) # YOUR CODE ENDS HERE # Save information in "cache" for the backprop cache = (A_prev, W, b, hparameters) return Z, cache np.random.seed(1) A_prev = np.random.randn(2, 5, 7, 4) W = np.random.randn(3, 3, 4, 8) b = np.random.randn(1, 1, 1, 8) hparameters = {"pad" : 1, "stride": 2} Z, cache_conv = conv_forward(A_prev, W, b, hparameters) print("Z's mean =\n", np.mean(Z)) print("Z[0,2,1] =\n", Z[0, 2, 1]) print("cache_conv[0][1][2][3] =\n", cache_conv[0][1][2][3]) conv_forward_test(conv_forward)
Z's mean = 0.5511276474566768 Z[0,2,1] = [-2.17796037 8.07171329 -0.5772704 3.36286738 4.48113645 -2.89198428 10.99288867 3.03171932] cache_conv[0][1][2][3] = [-1.1191154 1.9560789 -0.3264995 -1.34267579] All tests passed!
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
Finally, a CONV layer should also contain an activation, in which case you would add the following line of code:```python Convolve the window to get back one output neuronZ[i, h, w, c] = ... Apply activationA[i, h, w, c] = activation(Z[i, h, w, c])```You don't need to do it here, however. 4 - Pooling Layer The pooling (POOL) layer reduces the height and width of the input. It helps reduce computation, as well as helps make feature detectors more invariant to its position in the input. The two types of pooling layers are: - Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output.- Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output.These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size $f$. This specifies the height and width of the $f \times f$ window you would compute a *max* or *average* over. 4.1 - Forward PoolingNow, you are going to implement MAX-POOL and AVG-POOL, in the same function. Exercise 4 - pool_forwardImplement the forward pass of the pooling layer. Follow the hints in the comments below.**Reminder**:As there's no padding, the formulas binding the output shape of the pooling to the input shape is:$$n_H = \Bigl\lfloor \frac{n_{H_{prev}} - f}{stride} \Bigr\rfloor +1$$$$n_W = \Bigl\lfloor \frac{n_{W_{prev}} - f}{stride} \Bigr\rfloor +1$$$$n_C = n_{C_{prev}}$$
# GRADED FUNCTION: pool_forward def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C) cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters """ # Retrieve dimensions from the input shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve hyperparameters from "hparameters" f = hparameters["f"] stride = hparameters["stride"] # Define the dimensions of the output n_H = int(1 + (n_H_prev - f) / stride) n_W = int(1 + (n_W_prev - f) / stride) n_C = n_C_prev # Initialize output matrix A A = np.zeros((m, n_H, n_W, n_C)) # for i in range(None): # loop over the training examples # for h in range(None): # loop on the vertical axis of the output volume # Find the vertical start and end of the current "slice" (≈2 lines) # vert_start = None # vert_end = None # for w in range(None): # loop on the horizontal axis of the output volume # Find the vertical start and end of the current "slice" (≈2 lines) # horiz_start = None # horiz_end = None # for c in range (None): # loop over the channels of the output volume # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line) # a_prev_slice = None # Compute the pooling operation on the slice. # Use an if statement to differentiate the modes. # Use np.max and np.mean. # if mode == "max": # A[i, h, w, c] = None # elif mode == "average": # A[i, h, w, c] = None # YOUR CODE STARTS HERE for i in range(m): for h in range(n_H): vert_start = h*stride vert_end = vert_start + f for w in range(n_W): horiz_start = w*stride horiz_end = horiz_start + f for c in range(n_C): a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c] if mode == "max": A[i, h, w, c] = np.max(a_prev_slice) elif mode == "average": A[i, h, w, c] = np.mean(a_prev_slice) # YOUR CODE ENDS HERE # Store the input and hparameters in "cache" for pool_backward() cache = (A_prev, hparameters) # Making sure your output shape is correct #assert(A.shape == (m, n_H, n_W, n_C)) return A, cache # Case 1: stride of 1 np.random.seed(1) A_prev = np.random.randn(2, 5, 5, 3) hparameters = {"stride" : 1, "f": 3} A, cache = pool_forward(A_prev, hparameters, mode = "max") print("mode = max") print("A.shape = " + str(A.shape)) print("A[1, 1] =\n", A[1, 1]) A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mode = average") print("A.shape = " + str(A.shape)) print("A[1, 1] =\n", A[1, 1]) pool_forward_test(pool_forward)
mode = max A.shape = (2, 3, 3, 3) A[1, 1] = [[1.96710175 0.84616065 1.27375593] [1.96710175 0.84616065 1.23616403] [1.62765075 1.12141771 1.2245077 ]] mode = average A.shape = (2, 3, 3, 3) A[1, 1] = [[ 0.44497696 -0.00261695 -0.31040307] [ 0.50811474 -0.23493734 -0.23961183] [ 0.11872677 0.17255229 -0.22112197]] All tests passed!
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
**Expected output**```mode = maxA.shape = (2, 3, 3, 3)A[1, 1] = [[1.96710175 0.84616065 1.27375593] [1.96710175 0.84616065 1.23616403] [1.62765075 1.12141771 1.2245077 ]]mode = averageA.shape = (2, 3, 3, 3)A[1, 1] = [[ 0.44497696 -0.00261695 -0.31040307] [ 0.50811474 -0.23493734 -0.23961183] [ 0.11872677 0.17255229 -0.22112197]]```
# Case 2: stride of 2 np.random.seed(1) A_prev = np.random.randn(2, 5, 5, 3) hparameters = {"stride" : 2, "f": 3} A, cache = pool_forward(A_prev, hparameters) print("mode = max") print("A.shape = " + str(A.shape)) print("A[0] =\n", A[0]) print() A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mode = average") print("A.shape = " + str(A.shape)) print("A[1] =\n", A[1])
mode = max A.shape = (2, 2, 2, 3) A[0] = [[[1.74481176 0.90159072 1.65980218] [1.74481176 1.6924546 1.65980218]] [[1.13162939 1.51981682 2.18557541] [1.13162939 1.6924546 2.18557541]]] mode = average A.shape = (2, 2, 2, 3) A[1] = [[[-0.17313416 0.32377198 -0.34317572] [ 0.02030094 0.14141479 -0.01231585]] [[ 0.42944926 0.08446996 -0.27290905] [ 0.15077452 0.28911175 0.00123239]]]
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
**Expected Output:** ```mode = maxA.shape = (2, 2, 2, 3)A[0] = [[[1.74481176 0.90159072 1.65980218] [1.74481176 1.6924546 1.65980218]] [[1.13162939 1.51981682 2.18557541] [1.13162939 1.6924546 2.18557541]]]mode = averageA.shape = (2, 2, 2, 3)A[1] = [[[-0.17313416 0.32377198 -0.34317572] [ 0.02030094 0.14141479 -0.01231585]] [[ 0.42944926 0.08446996 -0.27290905] [ 0.15077452 0.28911175 0.00123239]]]``` **What you should remember**:* A convolution extracts features from an input image by taking the dot product between the input data and a 3D array of weights (the filter). * The 2D output of the convolution is called the feature map* A convolution layer is where the filter slides over the image and computes the dot product * This transforms the input volume into an output volume of different size * Zero padding helps keep more information at the image borders, and is helpful for building deeper networks, because you can build a CONV layer without shrinking the height and width of the volumes* Pooling layers gradually reduce the height and width of the input by sliding a 2D window over each specified region, then summarizing the features in that region **Congratulations**! You have now implemented the forward passes of all the layers of a convolutional network. Great work!The remainder of this notebook is optional, and will not be graded. If you carry on, just remember to hit the Submit button to submit your work for grading first. 5 - Backpropagation in Convolutional Neural Networks (OPTIONAL / UNGRADED)In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers don't need to bother with the details of the backward pass. The backward pass for convolutional networks is complicated. If you wish, you can work through this optional portion of the notebook to get a sense of what backprop in a convolutional network looks like. When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks you can calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial and were not derived in lecture, but are briefly presented below. 5.1 - Convolutional Layer Backward Pass Let's start by implementing the backward pass for a CONV layer. 5.1.1 - Computing dA:This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example:$$dA \mathrel{+}= \sum _{h=0} ^{n_H} \sum_{w=0} ^{n_W} W_c \times dZ_{hw} \tag{1}$$Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, you multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, you are just adding the gradients of all the a_slices. In code, inside the appropriate for-loops, this formula translates into:```pythonda_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]``` 5.1.2 - Computing dW:This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss:$$dW_c \mathrel{+}= \sum _{h=0} ^{n_H} \sum_{w=0} ^ {n_W} a_{slice} \times dZ_{hw} \tag{2}$$Where $a_{slice}$ corresponds to the slice which was used to generate the activation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$. In code, inside the appropriate for-loops, this formula translates into:```pythondW[:,:,:,c] \mathrel{+}= a_slice * dZ[i, h, w, c]``` 5.1.3 - Computing db:This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$:$$db = \sum_h \sum_w dZ_{hw} \tag{3}$$As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost. In code, inside the appropriate for-loops, this formula translates into:```pythondb[:,:,:,c] += dZ[i, h, w, c]``` Exercise 5 - conv_backwardImplement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above.
def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv_forward() Returns: dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev), numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) dW -- gradient of the cost with respect to the weights of the conv layer (W) numpy array of shape (f, f, n_C_prev, n_C) db -- gradient of the cost with respect to the biases of the conv layer (b) numpy array of shape (1, 1, 1, n_C) """ # Retrieve information from "cache" # (A_prev, W, b, hparameters) = None # Retrieve dimensions from A_prev's shape # (m, n_H_prev, n_W_prev, n_C_prev) = None # Retrieve dimensions from W's shape # (f, f, n_C_prev, n_C) = None # Retrieve information from "hparameters" # stride = None # pad = None # Retrieve dimensions from dZ's shape # (m, n_H, n_W, n_C) = None # Initialize dA_prev, dW, db with the correct shapes # dA_prev = None # dW = None # db = None # Pad A_prev and dA_prev # A_prev_pad = zero_pad(A_prev, pad) # dA_prev_pad = zero_pad(dA_prev, pad) #for i in range(m): # loop over the training examples # select ith training example from A_prev_pad and dA_prev_pad # a_prev_pad = None # da_prev_pad = None #for h in range(n_H): # loop over vertical axis of the output volume # for w in range(n_W): # loop over horizontal axis of the output volume # for c in range(n_C): # loop over the channels of the output volume # Find the corners of the current "slice" # vert_start = None # vert_end = None # horiz_start = None # horiz_end = None # Use the corners to define the slice from a_prev_pad # a_slice = None # Update gradients for the window and the filter's parameters using the code formulas given above # da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += None # dW[:,:,:,c] += None # db[:,:,:,c] += None # Set the ith training example's dA_prev to the unpadded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :]) # dA_prev[i, :, :, :] = None # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE # Making sure your output shape is correct assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev)) return dA_prev, dW, db # We'll run conv_forward to initialize the 'Z' and 'cache_conv", # which we'll use to test the conv_backward function np.random.seed(1) A_prev = np.random.randn(10, 4, 4, 3) W = np.random.randn(2, 2, 3, 8) b = np.random.randn(1, 1, 1, 8) hparameters = {"pad" : 2, "stride": 2} Z, cache_conv = conv_forward(A_prev, W, b, hparameters) # Test conv_backward dA, dW, db = conv_backward(Z, cache_conv) print("dA_mean =", np.mean(dA)) print("dW_mean =", np.mean(dW)) print("db_mean =", np.mean(db)) assert type(dA) == np.ndarray, "Output must be a np.ndarray" assert type(dW) == np.ndarray, "Output must be a np.ndarray" assert type(db) == np.ndarray, "Output must be a np.ndarray" assert dA.shape == (10, 4, 4, 3), f"Wrong shape for dA {dA.shape} != (10, 4, 4, 3)" assert dW.shape == (2, 2, 3, 8), f"Wrong shape for dW {dW.shape} != (2, 2, 3, 8)" assert db.shape == (1, 1, 1, 8), f"Wrong shape for db {db.shape} != (1, 1, 1, 8)" assert np.isclose(np.mean(dA), 1.4524377), "Wrong values for dA" assert np.isclose(np.mean(dW), 1.7269914), "Wrong values for dW" assert np.isclose(np.mean(db), 7.8392325), "Wrong values for db" print("\033[92m All tests passed.")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
**Expected Output**: dA_mean 1.45243777754 dW_mean 1.72699145831 db_mean 7.83923256462 5.2 Pooling Layer - Backward PassNext, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagate the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer. 5.2.1 Max Pooling - Backward Pass Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following: $$ X = \begin{bmatrix}1 && 3 \\4 && 2\end{bmatrix} \quad \rightarrow \quad M =\begin{bmatrix}0 && 0 \\1 && 0\end{bmatrix}\tag{4}$$As you can see, this function creates a "mask" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling is similar to this, but uses a different mask. Exercise 6 - create_mask_from_windowImplement `create_mask_from_window()`. This function will be helpful for pooling backward. Hints:- [np.max()]() may be helpful. It computes the maximum of an array.- If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that:```A[i,j] = True if X[i,j] = xA[i,j] = False if X[i,j] != x```- Here, you don't need to consider cases where there are several maxima in a matrix.
def create_mask_from_window(x): """ Creates a mask from an input matrix x, to identify the max entry of x. Arguments: x -- Array of shape (f, f) Returns: mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x. """ # (≈1 line) # mask = None # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE return mask np.random.seed(1) x = np.random.randn(2, 3) mask = create_mask_from_window(x) print('x = ', x) print("mask = ", mask) x = np.array([[-1, 2, 3], [2, -3, 2], [1, 5, -2]]) y = np.array([[False, False, False], [False, False, False], [False, True, False]]) mask = create_mask_from_window(x) assert type(mask) == np.ndarray, "Output must be a np.ndarray" assert mask.shape == x.shape, "Input and output shapes must match" assert np.allclose(mask, y), "Wrong output. The True value must be at position (2, 1)" print("\033[92m All tests passed.")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
**Expected Output:** **x =**[[ 1.62434536 -0.61175641 -0.52817175] [-1.07296862 0.86540763 -2.3015387 ]] mask =[[ True False False] [False False False]] Why keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will "propagate" the gradient back to this particular input value that had influenced the cost. 5.2.2 - Average Pooling - Backward Pass In max pooling, for each input window, all the "influence" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this.For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like: $$ dZ = 1 \quad \rightarrow \quad dZ =\begin{bmatrix}1/4 && 1/4 \\1/4 && 1/4\end{bmatrix}\tag{5}$$This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average. Exercise 7 - distribute_valueImplement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html)
def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we distributed the value of dz """ # Retrieve dimensions from shape (≈1 line) # (n_H, n_W) = None # Compute the value to distribute on the matrix (≈1 line) # average = None # Create a matrix where every entry is the "average" value (≈1 line) # a = None # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE return a a = distribute_value(2, (2, 2)) print('distributed value =', a) assert type(a) == np.ndarray, "Output must be a np.ndarray" assert a.shape == (2, 2), f"Wrong shape {a.shape} != (2, 2)" assert np.sum(a) == 2, "Values must sum to 2" a = distribute_value(100, (10, 10)) assert type(a) == np.ndarray, "Output must be a np.ndarray" assert a.shape == (10, 10), f"Wrong shape {a.shape} != (10, 10)" assert np.sum(a) == 100, "Values must sum to 100" print("\033[92m All tests passed.")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
**Expected Output**: distributed_value =[[ 0.5 0.5] [ 0.5 0.5]] 5.2.3 Putting it Together: Pooling Backward You now have everything you need to compute backward propagation on a pooling layer. Exercise 8 - pool_backwardImplement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dA.
def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev """ # Retrieve information from cache (≈1 line) # (A_prev, hparameters) = None # Retrieve hyperparameters from "hparameters" (≈2 lines) # stride = None # f = None # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines) # m, n_H_prev, n_W_prev, n_C_prev = None # m, n_H, n_W, n_C = None # Initialize dA_prev with zeros (≈1 line) # dA_prev = None # for i in range(None): # loop over the training examples # select training example from A_prev (≈1 line) # a_prev = None # for h in range(n_H): # loop on the vertical axis # for w in range(n_W): # loop on the horizontal axis # for c in range(n_C): # loop over the channels (depth) # Find the corners of the current "slice" (≈4 lines) # vert_start = None # vert_end = None # horiz_start = None # horiz_end = None # Compute the backward propagation in both modes. # if mode == "max": # Use the corners and "c" to define the current slice from a_prev (≈1 line) # a_prev_slice = None # Create the mask from a_prev_slice (≈1 line) # mask = None # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line) # dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None # elif mode == "average": # Get the value da from dA (≈1 line) # da = None # Define the shape of the filter as fxf (≈1 line) # shape = None # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line) # dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE # Making sure your output shape is correct assert(dA_prev.shape == A_prev.shape) return dA_prev np.random.seed(1) A_prev = np.random.randn(5, 5, 3, 2) hparameters = {"stride" : 1, "f": 2} A, cache = pool_forward(A_prev, hparameters) print(A.shape) print(cache[0].shape) dA = np.random.randn(5, 4, 2, 2) dA_prev1 = pool_backward(dA, cache, mode = "max") print("mode = max") print('mean of dA = ', np.mean(dA)) print('dA_prev1[1,1] = ', dA_prev1[1, 1]) print() dA_prev2 = pool_backward(dA, cache, mode = "average") print("mode = average") print('mean of dA = ', np.mean(dA)) print('dA_prev2[1,1] = ', dA_prev2[1, 1]) assert type(dA_prev1) == np.ndarray, "Wrong type" assert dA_prev1.shape == (5, 5, 3, 2), f"Wrong shape {dA_prev1.shape} != (5, 5, 3, 2)" assert np.allclose(dA_prev1[1, 1], [[0, 0], [ 5.05844394, -1.68282702], [ 0, 0]]), "Wrong values for mode max" assert np.allclose(dA_prev2[1, 1], [[0.08485462, 0.2787552], [1.26461098, -0.25749373], [1.17975636, -0.53624893]]), "Wrong values for mode average" print("\033[92m All tests passed.")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/Week 1/Convolution_model_Step_by_Step_v1.ipynb
Bo-Feng-1024/Soursera-Deep-Learning-Specialization
Regression with BIWI head pose dataset This is a more advanced example to show how to create custom datasets and do regression with images. Our task is to find the center of the head in each image. The data comes from the [BIWI head pose dataset](https://data.vision.ee.ethz.ch/cvl/gfanelli/head_pose/head_forest.htmldb), thanks to Gabriele Fanelli et al. We have converted the images to jpeg format, so you should download the converted dataset from [this link](https://s3.amazonaws.com/fast-ai-imagelocal/biwi_head_pose.tgz).
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai import * from fastai.vision import *
_____no_output_____
Apache-2.0
nbs/dl1/lesson3-head-pose.ipynb
perrychu/course-v3
Getting and converting the data
path = untar_data(URLs.BIWI_HEAD_POSE) cal = np.genfromtxt(path/'01'/'rgb.cal', skip_footer=6); cal fname = '09/frame_00667_rgb.jpg' def img2txt_name(f): return path/f'{str(f)[:-7]}pose.txt' img = open_image(path/fname) img.show() ctr = np.genfromtxt(img2txt_name(fname), skip_header=3); ctr def convert_biwi(coords): c1 = coords[0] * cal[0][0]/coords[2] + cal[0][2] c2 = coords[1] * cal[1][1]/coords[2] + cal[1][2] return tensor([c2,c1]) def get_ctr(f): ctr = np.genfromtxt(img2txt_name(f), skip_header=3) return convert_biwi(ctr) def get_ip(img,pts): return ImagePoints(FlowField(img.size, pts), scale=True) get_ctr(fname) ctr = get_ctr(fname) img.show(y=get_ip(img, ctr), figsize=(6, 6))
_____no_output_____
Apache-2.0
nbs/dl1/lesson3-head-pose.ipynb
perrychu/course-v3
Creating a dataset
data = (ImageItemList.from_folder(path) .split_by_valid_func(lambda o: o.parent.name=='13') .label_from_func(get_ctr, label_cls=PointsItemList) .transform(get_transforms(), tfm_y=True, size=(120,160)) .databunch().normalize(imagenet_stats) ) data.show_batch(3, figsize=(9,6))
_____no_output_____
Apache-2.0
nbs/dl1/lesson3-head-pose.ipynb
perrychu/course-v3
Train model
learn = create_cnn(data, models.resnet34) learn.lr_find() learn.recorder.plot() lr = 2e-2 learn.fit_one_cycle(5, slice(lr)) learn.save('stage-1') learn.load('stage-1'); learn.show_results()
_____no_output_____
Apache-2.0
nbs/dl1/lesson3-head-pose.ipynb
perrychu/course-v3
Choosing the number of segments - Elbow chart method This document illustrates how to decide the number of segments (optimal $k$) using elbow charts. Introducing elbow chart method **When we should (not) add more clusters**: Ideally, the lower the $SSE$ is, the better is the clustering. Although adding more clusters (a higher $k$) always reduces $SSE$, adding too many clusters can be managerially cumbersome (e.g., when designing individual strategies for each segment) and redundant (e.g., nearby clusters have little differences). Hence, we want to add more clusters if doing so can **significantly** reduce $SSE$, and stop adding clusters if doing so **doesn't reduce $SSE$ by much**. **How elbow chart works**: The elbow chart plots a curve of how SSE changes with the number of clusters. Because adding more clusters will reduce SSE, the curve will be downward sloping, and the curve is steeper if adding one more cluster ($k \rightarrow k+1$) reduces SSE by a greater amount. We should choose the cluster number $k$ that corresponds to the "elbow point" in the plot (the kink where the curve exhibits an "L" shape). The elbow point indicates that the curve is steeper on the left ($SSE$ decreases a lot from $k-1$ to $k$), and is flatter on the right ($SSE$ decreases not much from $k$ to $k+1$). **Procedure**: Suppose we want to create no more than $K$ segments. The procedure is as follows:1. For $k$ from $1$ to $K$: run k-mean algorithm with $k$ clusters, and calculate and record the $SSE$.2. Plot $SSE$ over the number of segments $k$ to get the elbow chart.3. Find $k$ that corresponds to the elbow point. This is the optimal number of segments to segment consumers.4. Use the optimal $k$ to run k-mean algorithm to segment consumers. We will use "MallCustomersTwoVariables.csv" for analysis. Loading data and preprocessing This section will generate the normalized dataframe, `df_normalized`, for k-mean algorithm.
# importing packages import numpy as np import pandas as pd from sklearn.cluster import KMeans # Use "sklearn/cluster/KMeans" for clustering analysis # importing data and renaming variables url = "https://raw.githubusercontent.com/zoutianxin1992/MarketingAnalyticsPython/main/Marketing%20Analytics%20in%20Python/Segmentation/Datasets/MallCustomersTwoVariables.csv" df = pd.read_csv(url,index_col=0) # use the first column (customer id) as index df = df.rename(columns = {"Annual Income (k$)":"annual_income","Spending Score (1-100)":"spending_score"}) # normalizing the data for k-mean algorithm df_normalized = (df-df.min())/(df.max()-df.min()) # By default, pandas calculate maximums and minimums by columns, which serves our purpose.
_____no_output_____
MIT
Marketing Analytics in Python/Segmentation/Notebooks/sgmt_numvar_ElbowChart.ipynb
zoutianxin1992/MarketingAnalyticsPython
Calculate $SSE$ for each $k$ For exposition, we will create no more than $K = 10$ clusters, and calculate $SSE$s when $k = 1,2,3,...,K$. This can be achieved with a for loop.(If you use Windows, you may see a warning of "KMeans is known to have a memory leak...." Don't worry in our case because both our data size and the number of clusters are much smaller than when the problem will happen.)
K = 10 # K is the maximum number of clusters we will check store_SSE = np.zeros(K) # create a vector to store SSE's. The k-th entry will be the SSE with k clusters. for k in range(1, K+1): # try k from 1 to K kmeanSpec = KMeans(n_clusters = k, n_init = 100) # set up k-mean model with k clusters kmean_result = kmeanSpec.fit(df_normalized) # run k-mean on normalized data store_SSE[k-1] = kmeanSpec.inertia_ # store the SSE (.inertia_) in the k-th entry of store_SSE
C:\Users\zoutianxin\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\cluster\_kmeans.py:882: UserWarning: KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=1. f"KMeans is known to have a memory leak on Windows "
MIT
Marketing Analytics in Python/Segmentation/Notebooks/sgmt_numvar_ElbowChart.ipynb
zoutianxin1992/MarketingAnalyticsPython
Generate elbow chart
from matplotlib import pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = [12,8] # set figure size to be 12*8 inch plt.plot(range(1, K+1), store_SSE) plt.xticks(range(1, K+1), fontsize = 18) plt.yticks(fontsize = 18) plt.ylabel("SSE",fontsize = 18) plt.xlabel("number of clusters", fontsize = 18)
_____no_output_____
MIT
Marketing Analytics in Python/Segmentation/Notebooks/sgmt_numvar_ElbowChart.ipynb
zoutianxin1992/MarketingAnalyticsPython
DIMAML for Autoencoder modelsTraining is on Celeba. Evaluation is on Tiny ImageNet
%load_ext autoreload %autoreload 2 %env CUDA_VISIBLE_DEVICES=0 import os, sys, time sys.path.insert(0, '..') import lib import math import numpy as np from copy import deepcopy import torch, torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn-darkgrid') plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['ps.fonttype'] = 42 # For reproducibility import random seed = random.randint(0, 2 ** 32 - 1) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False print(seed)
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Setting
model_type = 'AE' # Dataset data_dir = './data' train_batch_size = 128 valid_batch_size = 256 test_batch_size = 128 num_workers = 3 pin_memory = True device = 'cuda' if torch.cuda.is_available() else 'cpu' # AE latent_dim = 64 loss_function = F.mse_loss # MAML max_steps = 1500 inner_loop_steps_in_epoch = 200 inner_loop_epochs = 3 inner_loop_steps = inner_loop_steps_in_epoch * inner_loop_epochs meta_grad_clip = 10. loss_kwargs={'reduction':'mean'} loss_interval = 50 first_val_step = 200 assert (inner_loop_steps - first_val_step) % loss_interval == 0 validation_steps = int((inner_loop_steps - first_val_step) / loss_interval + 1) # Inner optimizer inner_optimizer_type='momentum' inner_optimizer_kwargs = dict( lr=0.01, momentum=0.9, nesterov=False, weight_decay=0.0 ) # Meta optimizer meta_learning_rate = 1e-4 meta_betas = (0.9, 0.997) meta_decay_interval = max_steps checkpoint_steps = 15 recovery_step = None kwargs = dict( first_valid_step=first_val_step, valid_loss_interval=loss_interval, loss_kwargs=loss_kwargs, ) exp_name = f"{model_type}{latent_dim}_celeba_{inner_optimizer_type}" + \ f"_steps{inner_loop_steps}_interval{loss_interval}" + \ f"_tr_bs{train_batch_size}_val_bs{valid_batch_size}_seed_{seed}" print("Experiment name: ", exp_name) logs_path = "./logs/{}".format(exp_name) assert recovery_step is not None or not os.path.exists(logs_path) # !rm -rf {logs_path}
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Prepare the CelebA dataset
import pandas as pd import shutil celeba_data_dir = 'data/celeba/' data = pd.read_csv(os.path.join(celeba_data_dir, 'list_eval_partition.csv')) try: for partition in ['train', 'val', 'test']: os.makedirs(os.path.join(celeba_data_dir, partition)) os.makedirs(os.path.join(celeba_data_dir, partition, 'images')) for i in data.index: partition = data.loc[i].partition src_path = os.path.join(celeba_data_dir, 'img_align_celeba/img_align_celeba', data.loc[i].image_id) if partition == 0: shutil.copyfile(src_path, os.path.join(celeba_data_dir, 'train', 'images', data.loc[i].image_id)) elif partition == 1: shutil.copyfile(src_path, os.path.join(celeba_data_dir, 'val', 'images', data.loc[i].image_id)) elif partition == 2: shutil.copyfile(src_path, os.path.join(celeba_data_dir, 'test', 'images', data.loc[i].image_id)) except FileExistsError: print('\'train\', \'val\', \'test\' already exist. Probably, you do not want to copy data again') from torchvision import transforms, datasets from torch.utils.data import DataLoader celeba_transforms = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), ]) # Create the train set celeba_train_dataset = datasets.ImageFolder(celeba_data_dir+'train', transform=celeba_transforms) celeba_train_images = torch.cat([celeba_train_dataset[i][0][None] for i in range(len(celeba_train_dataset))]) celeba_mean_image = celeba_train_images.mean(0) celeba_std_image = celeba_train_images.std(0) celeba_train_images = (celeba_train_images - celeba_mean_image) / celeba_std_image # Create the val set celeba_valid_dataset = datasets.ImageFolder(celeba_data_dir+'val', celeba_transforms) celeba_valid_images = torch.cat([celeba_valid_dataset[i][0][None] for i in range(len(celeba_valid_dataset))]) celeba_valid_images = (celeba_valid_images - celeba_mean_image) / celeba_std_image # Create the test set celeba_test_dataset = datasets.ImageFolder(celeba_data_dir+'test', celeba_transforms) celeba_test_images = torch.cat([celeba_test_dataset[i][0][None] for i in range(len(celeba_test_dataset))]) celeba_test_images = (celeba_test_images - celeba_mean_image) / celeba_std_image # Create data loaders train_loader = torch.utils.data.DataLoader(celeba_train_images, batch_size=train_batch_size, shuffle=True, pin_memory=pin_memory, num_workers=num_workers) valid_loader = torch.utils.data.DataLoader(celeba_valid_images, batch_size=valid_batch_size, shuffle=True, pin_memory=pin_memory, num_workers=num_workers) test_loader = torch.utils.data.DataLoader(celeba_test_images, batch_size=test_batch_size, pin_memory=pin_memory, num_workers=num_workers)
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Create the model and meta-optimizer
optimizer = lib.make_inner_optimizer(inner_optimizer_type, **inner_optimizer_kwargs) model = lib.models.AE(latent_dim) maml = lib.MAML(model, model_type, optimizer=optimizer, checkpoint_steps=checkpoint_steps, loss_function=loss_function ).to(device)
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Trainer
def samples_batches(dataloader, num_batches): x_batches = [] for batch_i, x_batch in enumerate(dataloader): if batch_i >= num_batches: break x_batches.append(x_batch) return x_batches class TrainerAE(lib.Trainer): def train_on_batch(self, train_loader, valid_loader, prefix='train/', **kwargs): """ Performs a single gradient update and reports metrics """ # Sample train and val batches x_batches = [] for _ in range(inner_loop_epochs): x_batches.extend(samples_batches(train_loader, inner_loop_steps_in_epoch)) x_val_batches = samples_batches(valid_loader, validation_steps) # Perform a meta training step self.meta_optimizer.zero_grad() with lib.training_mode(self.maml, is_train=True): self.maml.resample_parameters() _updated_model, train_loss_history, valid_loss_history, *etc = \ self.maml.forward(x_batches, x_batches, x_val_batches, x_val_batches, device=self.device, **kwargs) train_loss = torch.cat(train_loss_history).mean() valid_loss = torch.cat(valid_loss_history).mean() if len(valid_loss_history) > 0 else torch.zeros(1) valid_loss.backward() # Check gradients grad_norm = lib.utils.total_norm_frobenius(self.maml.initializers.parameters()) self.writer.add_scalar(prefix + "grad_norm", grad_norm, self.total_steps) bad_grad = not math.isfinite(grad_norm) if not bad_grad: nn.utils.clip_grad_norm_(list(self.maml.initializers.parameters()), meta_grad_clip) else: print("Fix bad grad. Loss {} | Grad {}".format(train_loss.item(), grad_norm)) for param in self.maml.initializers.parameters(): param.grad = torch.where(torch.isfinite(param.grad), param.grad, torch.zeros_like(param.grad)) self.meta_optimizer.step() return self.record(train_loss=train_loss.item(), valid_loss=valid_loss.item(), prefix=prefix) def evaluate_metrics(self, train_loader, test_loader, prefix='val/', **kwargs): """ Predicts and evaluates metrics over the entire dataset """ torch.cuda.empty_cache() print('Baseline') self.maml.resample_parameters(initializers=self.maml.untrained_initializers, is_final=True) base_model = deepcopy(self.maml.model) base_train_loss_history, base_test_loss_history = eval_model(base_model, train_loader, test_loader, device=self.device, **kwargs) print('DIMAML') self.maml.resample_parameters(is_final=True) maml_model = deepcopy(self.maml.model) maml_train_loss_history, maml_test_loss_history = eval_model(maml_model, train_loader, test_loader, device=self.device, **kwargs) lib.utils.ae_draw_plots(base_train_loss_history, base_test_loss_history, maml_train_loss_history, maml_test_loss_history) self.writer.add_scalar(prefix + "train_AUC", sum(maml_train_loss_history), self.total_steps) self.writer.add_scalar(prefix + "test_AUC", sum(maml_test_loss_history), self.total_steps) self.writer.add_scalar(prefix + "test_loss", maml_test_loss_history[-1], self.total_steps) ######################## # Generate Train Batch # ######################## def generate_train_batches(train_loader, batches_in_epoch=150): x_batches = [] for batch_i, x_batch in enumerate(train_loader): if batch_i >= batches_in_epoch: break x_batches.append(x_batch) assert len(x_batches) == batches_in_epoch local_x = torch.cat(x_batches, dim=0) return DataLoader(local_x, batch_size=train_batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory) ################## # Eval functions # ################## @torch.no_grad() def compute_test_loss(model, loss_function, test_loader, device='cuda'): model.eval() test_loss = 0. for batch_test in test_loader: if isinstance(batch_test, (list, tuple)): x_test = batch_test[0].to(device) elif isinstance(batch_test, torch.Tensor): x_test = batch_test.to(device) else: raise Exception("Wrong batch") preds = model(x_test) test_loss += loss_function(preds, x_test) * x_test.shape[0] test_loss /= len(test_loader.dataset) model.train() return test_loss.item() def eval_model(model, train_loader, test_loader, batches_in_epoch=150, epochs=3, test_loss_interval=50, device='cuda', **kwargs): optimizer = lib.optimizers.make_eval_inner_optimizer( maml, model, inner_optimizer_type, **inner_optimizer_kwargs ) train_loss_history = [] test_loss_history = [] training_mode = model.training total_iters = 0 for epoch in range(1, epochs + 1): model.train() for x_batch in train_loader: optimizer.zero_grad() x_batch = x_batch.to(device) preds = model(x_batch) loss = loss_function(preds, x_batch) loss.backward() optimizer.step() train_loss_history.append(loss.item()) if (total_iters == 0) or (total_iters + 1) % test_loss_interval == 0: model.eval() test_loss = compute_test_loss(model, loss_function, test_loader, device=device) print("Epoch {} | Total Iteration {} | Loss {}".format(epoch, total_iters+1, test_loss)) test_loss_history.append(test_loss) model.train() total_iters += 1 model.train(training_mode) return train_loss_history, test_loss_history train_loss_history = [] valid_loss_history = [] trainer = TrainerAE(maml, meta_lr=meta_learning_rate, meta_betas=meta_betas, meta_grad_clip=meta_grad_clip, exp_name=exp_name, recovery_step=recovery_step) from IPython.display import clear_output lib.free_memory() t0 = time.time() while trainer.total_steps <= max_steps: local_train_loader = generate_train_batches(train_loader, inner_loop_steps_in_epoch) with lib.activate_context_batchnorm(maml.model): metrics = trainer.train_on_batch( local_train_loader, valid_loader, **kwargs ) train_loss = metrics['train_loss'] train_loss_history.append(train_loss) valid_loss = metrics['valid_loss'] valid_loss_history.append(valid_loss) if trainer.total_steps % 20 == 0: clear_output(True) print("Step: %d | Time: %f | Train Loss %.5f | Valid loss %.5f" % (trainer.total_steps, time.time()-t0, train_loss, valid_loss)) plt.figure(figsize=[16, 5]) plt.subplot(1,2,1) plt.title('Train Loss over time') plt.plot(lib.utils.moving_average(train_loss_history, span=50)) plt.scatter(range(len(train_loss_history)), train_loss_history, alpha=0.1) plt.subplot(1,2,2) plt.title('Valid Loss over time') plt.plot(lib.utils.moving_average(valid_loss_history, span=50)) plt.scatter(range(len(valid_loss_history)), valid_loss_history, alpha=0.1) plt.show() trainer.evaluate_metrics(local_train_loader, test_loader, epochs=inner_loop_epochs, test_loss_interval=loss_interval) lib.utils.ae_visualize_pdf(maml) t0 = time.time() if trainer.total_steps % 100 == 0: trainer.save_model() trainer.total_steps += 1
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Probability Functions
lib.utils.ae_visualize_pdf(maml)
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Evaluation
torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = True def genOrthgonal(dim): a = torch.zeros((dim, dim)).normal_(0, 1) q, r = torch.qr(a) d = torch.diag(r, 0).sign() diag_size = d.size(0) d_exp = d.view(1, diag_size).expand(diag_size, diag_size) q.mul_(d_exp) return q def makeDeltaOrthogonal(weights, gain): rows = weights.size(0) cols = weights.size(1) if rows < cols: print("In_filters should not be greater than out_filters.") weights.data.fill_(0) dim = max(rows, cols) q = genOrthgonal(dim) mid1 = weights.size(2) // 2 mid2 = weights.size(3) // 2 with torch.no_grad(): weights[:, :, mid1, mid2] = q[:weights.size(0), :weights.size(1)] weights.mul_(gain) def gradient_quotient(loss, params, eps=1e-5): grad = torch.autograd.grad(loss, params, retain_graph=True, create_graph=True) prod = torch.autograd.grad(sum([(g**2).sum() / 2 for g in grad]), params, retain_graph=True, create_graph=True) out = sum([((g - p) / (g + eps * (2*(g >= 0).float() - 1).detach()) - 1).abs().sum() for g, p in zip(grad, prod)]) return out / sum([p.data.nelement() for p in params]) def metainit(model, criterion, x_size, lr=0.1, momentum=0.9, steps=200, eps=1e-5): model.eval() params = [p for p in model.parameters() if p.requires_grad and len(p.size()) >= 2] memory = [0] * len(params) for i in range(steps): input = torch.Tensor(*x_size).normal_(0, 1).cuda() loss = criterion(model(input), input) gq = gradient_quotient(loss, list(model.parameters()), eps) grad = torch.autograd.grad(gq, params) for j, (p, g_all) in enumerate(zip(params, grad)): norm = p.data.norm().item() g = torch.sign((p.data * g_all).sum() / norm) memory[j] = momentum * memory[j] - lr * g.item() new_norm = norm + memory[j] p.data.mul_(new_norm / (norm + eps)) print("%d/GQ = %.2f" % (i, gq.item()))
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Evalution on Tiny Imagenet
class PixelNormalize(object): def __init__(self, mean_image, std_image): self.mean_image = mean_image self.std_image = std_image def __call__(self, image): normalized_image = (image - self.mean_image) / self.std_image return normalized_image class Flip(object): def __call__(self, image): if random.random() > 0.5: return image.flip(-1) else: return image class CustomTensorDataset(torch.utils.data.Dataset): """ TensorDataset with support of transforms """ def __init__(self, *tensors, transform=None): assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors) self.tensors = tensors self.transform = transform def __getitem__(self, index): x = self.tensors[0][index] if self.transform: x = self.transform(x) return x def __len__(self): return self.tensors[0].size(0) # Load train and valid data from torchvision import transforms, datasets from torch.utils.data import DataLoader data_dir = 'data/tiny-imagenet-200/' train_image_dataset = datasets.ImageFolder(os.path.join(data_dir, 'train'), transforms.ToTensor()) train_images = torch.cat([train_image_dataset[i][0][None] for i in range(len(train_image_dataset))], dim=0) mean_image = train_images.mean(0) std_image = train_images.std(0) train_transforms = transforms.Compose([ Flip(), PixelNormalize(mean_image, std_image), ]) eval_transforms = transforms.Compose([ PixelNormalize(mean_image, std_image), ]) ti_train_dataset = CustomTensorDataset(train_images, transform=train_transforms) valid_image_dataset = datasets.ImageFolder(os.path.join(data_dir, 'val'), transforms.ToTensor()) valid_images = torch.cat([valid_image_dataset[i][0][None] for i in range(len(valid_image_dataset))], dim=0) ti_valid_dataset = CustomTensorDataset(valid_images, transform=eval_transforms) test_image_dataset = datasets.ImageFolder(os.path.join(data_dir, 'test'), transforms.ToTensor()) test_images = torch.cat([test_image_dataset[i][0][None] for i in range(len(test_image_dataset))], dim=0) ti_test_dataset = CustomTensorDataset(test_images, transform=eval_transforms) # Create data loaders ti_train_loader = DataLoader( ti_train_dataset, batch_size=train_batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory, ) ti_valid_loader = DataLoader( ti_valid_dataset, batch_size=valid_batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory, ) ti_test_loader = DataLoader( ti_test_dataset, batch_size=test_batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory ) num_reruns = 10 ti_batches_in_epoch = len(ti_train_loader) #782 - full epoch assert ti_batches_in_epoch == 782 ti_base_runs_10 = [] ti_base_runs_50 = [] ti_base_runs_100 = [] ti_metainit_runs_10 = [] ti_metainit_runs_50 = [] ti_metainit_runs_100 = [] ti_deltaorthogonal_runs_10 = [] ti_deltaorthogonal_runs_50 = [] ti_deltaorthogonal_runs_100 = [] ti_maml_runs_10 = [] ti_maml_runs_50 = [] ti_maml_runs_100 = [] for _ in range(num_reruns): print("Baseline") maml.resample_parameters(initializers=maml.untrained_initializers, is_final=True) base_model = deepcopy(maml.model) base_train_loss_history, base_test_loss_history = \ eval_model(base_model, ti_train_loader, ti_test_loader, epochs=100, test_loss_interval=10*ti_batches_in_epoch, device=device) print("MetaInit") batch_x = next(iter(ti_train_loader)) maml.resample_parameters(initializers=maml.untrained_initializers, is_final=True) metainit_model = deepcopy(maml.model) metainit(metainit_model, loss_function, batch_x.shape, steps=200) metainit_train_loss_history, metainit_test_loss_history = \ eval_model(metainit_model, ti_train_loader, ti_test_loader, batches_in_epoch=ti_batches_in_epoch, epochs=100, test_loss_interval=10*ti_batches_in_epoch, device=device) print("Delta Orthogonal") maml.resample_parameters(initializers=maml.untrained_initializers, is_final=True) deltaorthogonal_model = deepcopy(maml.model) for param in deltaorthogonal_model.parameters(): if len(param.size()) >= 4: makeDeltaOrthogonal(param, nn.init.calculate_gain('relu')) deltaorthogonal_train_loss_history, deltaorthogonal_test_loss_history = \ eval_model(deltaorthogonal_model, ti_train_loader, ti_test_loader, batches_in_epoch=ti_batches_in_epoch, epochs=100, test_loss_interval=10*ti_batches_in_epoch, device=device) ti_deltaorthogonal_runs_10.append(deltaorthogonal_test_loss_history[1]) ti_deltaorthogonal_runs_50.append(deltaorthogonal_test_loss_history[5]) ti_deltaorthogonal_runs_100.append(deltaorthogonal_test_loss_history[10]) print("DIMAML") maml.resample_parameters(is_final=True) maml_model = deepcopy(maml.model) maml_train_loss_history, maml_test_loss_history = \ eval_model(maml_model, ti_train_loader, ti_test_loader, epochs=100, test_loss_interval=10*ti_batches_in_epoch, device=device) ti_base_runs_10.append(base_test_loss_history[1]) ti_base_runs_50.append(base_test_loss_history[5]) ti_base_runs_100.append(base_test_loss_history[10]) ti_metainit_runs_10.append(metainit_test_loss_history[1]) ti_metainit_runs_50.append(metainit_test_loss_history[5]) ti_metainit_runs_100.append(metainit_test_loss_history[10]) ti_maml_runs_10.append(maml_test_loss_history[1]) ti_maml_runs_50.append(maml_test_loss_history[5]) ti_maml_runs_100.append(maml_test_loss_history[10]) print("Baseline 10 epoch: ", np.mean(ti_base_runs_10), np.std(ti_base_runs_10, ddof=1)) print("Baseline 50 epoch: ", np.mean(ti_base_runs_50), np.std(ti_base_runs_50, ddof=1)) print("Baseline 100 epoch: ", np.mean(ti_base_runs_100), np.std(ti_base_runs_100, ddof=1)) print() print("DeltaOrthogonal 10 epoch: ", np.mean(ti_deltaorthogonal_runs_10), np.std(ti_deltaorthogonal_runs_10, ddof=1)) print("DeltaOrthogonal 50 epoch: ", np.mean(ti_deltaorthogonal_runs_50), np.std(ti_deltaorthogonal_runs_50, ddof=1)) print("DeltaOrthogonal 100 epoch: ", np.mean(ti_deltaorthogonal_runs_100), np.std(ti_deltaorthogonal_runs_100, ddof=1)) print() print("MetaInit 10 epoch: ", np.mean(ti_metainit_runs_10), np.std(ti_metainit_runs_10, ddof=1)) print("MetaInit 50 epoch: ", np.mean(ti_metainit_runs_50), np.std(ti_metainit_runs_50, ddof=1)) print("MetaInit 100 epoch: ", np.mean(ti_metainit_runs_100), np.std(ti_metainit_runs_100, ddof=1)) print() print("DIMAML 10 epoch: ", np.mean(ti_maml_runs_10), np.std(ti_maml_runs_10, ddof=1)) print("DIMAML 50 epoch: ", np.mean(ti_maml_runs_50), np.std(ti_maml_runs_50, ddof=1)) print("DIMAML 100 epoch: ", np.mean(ti_maml_runs_100), np.std(ti_maml_runs_100, ddof=1))
_____no_output_____
Apache-2.0
notebooks/AE_CelebA_experiment.ipynb
yandex-research/learnable-init
Autonomous Driving - Car DetectionWelcome to the Week 3 programming assignment! In this notebook, you'll implement object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: [Redmon et al., 2016](https://arxiv.org/abs/1506.02640) and [Redmon and Farhadi, 2016](https://arxiv.org/abs/1612.08242). **By the end of this assignment, you'll be able to**:- Detect objects in a car detection dataset- Implement non-max suppression to increase accuracy- Implement intersection over union- Handle bounding boxes, a type of image annotation popular in deep learning Table of Contents- [Packages](0)- [1 - Problem Statement](1)- [2 - YOLO](2) - [2.1 - Model Details](2-1) - [2.2 - Filtering with a Threshold on Class Scores](2-2) - [Exercise 1 - yolo_filter_boxes](ex-1) - [2.3 - Non-max Suppression](2-3) - [Exercise 2 - iou](ex-2) - [2.4 - YOLO Non-max Suppression](2-4) - [Exercise 3 - yolo_non_max_suppression](ex-3) - [2.5 - Wrapping Up the Filtering](2-5) - [Exercise 4 - yolo_eval](ex-4)- [3 - Test YOLO Pre-trained Model on Images](3) - [3.1 - Defining Classes, Anchors and Image Shape](3-1) - [3.2 - Loading a Pre-trained Model](3-2) - [3.3 - Convert Output of the Model to Usable Bounding Box Tensors](3-3) - [3.4 - Filtering Boxes](3-4) - [3.5 - Run the YOLO on an Image](3-5)- [4 - Summary for YOLO](4)- [5 - References](5) PackagesRun the following cell to load the packages and dependencies that will come in handy as you build the object detector!
import argparse import os import matplotlib.pyplot as plt from matplotlib.pyplot import imshow import scipy.io import scipy.misc import numpy as np import pandas as pd import PIL from PIL import ImageFont, ImageDraw, Image import tensorflow as tf from tensorflow.python.framework.ops import EagerTensor from tensorflow.keras.models import load_model from yad2k.models.keras_yolo import yolo_head from yad2k.utils.utils import draw_boxes, get_colors_for_classes, scale_boxes, read_classes, read_anchors, preprocess_image %matplotlib inline
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
1 - Problem StatementYou are working on a self-driving car. Go you! As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds as you drive around. Pictures taken from a car-mounted camera while driving around Silicon Valley. Dataset provided by drive.ai.You've gathered all these images into a folder and labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like: Figure 1: Definition of a box If there are 80 classes you want the object detector to recognize, you can represent the class label $c$ either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1, and the rest of which are 0. The video lectures used the latter representation; in this notebook, you'll use both representations, depending on which is more convenient for a particular step. In this exercise, you'll discover how YOLO ("You Only Look Once") performs object detection, and then apply it to car detection. Because the YOLO model is very computationally expensive to train, the pre-trained weights are already loaded for you to use. 2 - YOLO "You Only Look Once" (YOLO) is a popular algorithm because it achieves high accuracy while also being able to run in real time. This algorithm "only looks once" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes. 2.1 - Model Details Inputs and outputs- The **input** is a batch of images, and each image has the shape (m, 608, 608, 3)- The **output** is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers $(p_c, b_x, b_y, b_h, b_w, c)$ as explained above. If you expand $c$ into an 80-dimensional vector, each bounding box is then represented by 85 numbers. Anchor Boxes* Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes. For this assignment, 5 anchor boxes were chosen for you (to cover the 80 classes), and stored in the file './model_data/yolo_anchors.txt'* The dimension for anchor boxes is the second to last dimension in the encoding: $(m, n_H,n_W,anchors,classes)$.* The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85). EncodingLet's look in greater detail at what this encoding represents. Figure 2 : Encoding architecture for YOLO If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object. Since you're using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.For simplicity, you'll flatten the last two dimensions of the shape (19, 19, 5, 85) encoding, so the output of the Deep CNN is (19, 19, 425). Figure 3 : Flattening the last two last dimensions Class scoreNow, for each box (of each cell) you'll compute the following element-wise product and extract a probability that the box contains a certain class. The class score is $score_{c,i} = p_{c} \times c_{i}$: the probability that there is an object $p_{c}$ times the probability that the object is a certain class $c_{i}$. Figure 4: Find the class detected by each box Example of figure 4* In figure 4, let's say for box 1 (cell 1), the probability that an object exists is $p_{1}=0.60$. So there's a 60% chance that an object exists in box 1 (cell 1). * The probability that the object is the class "category 3 (a car)" is $c_{3}=0.73$. * The score for box 1 and for category "3" is $score_{1,3}=0.60 \times 0.73 = 0.44$. * Let's say you calculate the score for all 80 classes in box 1, and find that the score for the car class (class 3) is the maximum. So you'll assign the score 0.44 and class "3" to this box "1". Visualizing classesHere's one way to visualize what YOLO is predicting on an image:- For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across the 80 classes, one maximum for each of the 5 anchor boxes).- Color that grid cell according to what object that grid cell considers the most likely.Doing this results in this picture: Figure 5: Each one of the 19x19 grid cells is colored according to which class has the largest predicted probability in that cell. Note that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm. Visualizing bounding boxesAnother way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this: Figure 6: Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes. Non-Max suppressionIn the figure above, the only boxes plotted are ones for which the model had assigned a high probability, but this is still too many boxes. You'd like to reduce the algorithm's output to a much smaller number of detected objects. To do so, you'll use **non-max suppression**. Specifically, you'll carry out these steps: - Get rid of boxes with a low score. Meaning, the box is not very confident about detecting a class, either due to the low probability of any object, or low probability of this particular class.- Select only one box when several boxes overlap with each other and detect the same object. 2.2 - Filtering with a Threshold on Class ScoresYou're going to first apply a filter by thresholding, meaning you'll get rid of any box for which the class "score" is less than a chosen threshold. The model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It's convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables: - `box_confidence`: tensor of shape $(19, 19, 5, 1)$ containing $p_c$ (confidence probability that there's some object) for each of the 5 boxes predicted in each of the 19x19 cells.- `boxes`: tensor of shape $(19, 19, 5, 4)$ containing the midpoint and dimensions $(b_x, b_y, b_h, b_w)$ for each of the 5 boxes in each cell.- `box_class_probs`: tensor of shape $(19, 19, 5, 80)$ containing the "class probabilities" $(c_1, c_2, ... c_{80})$ for each of the 80 classes for each of the 5 boxes per cell. Exercise 1 - yolo_filter_boxesImplement `yolo_filter_boxes()`.1. Compute box scores by doing the elementwise product as described in Figure 4 ($p \times c$). The following code may help you choose the right operator: ```pythona = np.random.randn(19, 19, 5, 1)b = np.random.randn(19, 19, 5, 80)c = a * b shape of c will be (19, 19, 5, 80)```This is an example of **broadcasting** (multiplying vectors of different sizes).2. For each box, find: - the index of the class with the maximum box score - the corresponding box score **Useful References** * [tf.math.argmax](https://www.tensorflow.org/api_docs/python/tf/math/argmax) * [tf.math.reduce_max](https://www.tensorflow.org/api_docs/python/tf/math/reduce_max) **Helpful Hints** * For the `axis` parameter of `argmax` and `reduce_max`, if you want to select the **last** axis, one way to do so is to set `axis=-1`. This is similar to Python array indexing, where you can select the last position of an array using `arrayname[-1]`. * Applying `reduce_max` normally collapses the axis for which the maximum is applied. `keepdims=False` is the default option, and allows that dimension to be removed. You don't need to keep the last dimension after applying the maximum here.3. Create a mask by using a threshold. As a reminder: `([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4)` returns: `[False, True, False, False, True]`. The mask should be `True` for the boxes you want to keep. 4. Use TensorFlow to apply the mask to `box_class_scores`, `boxes` and `box_classes` to filter out the boxes you don't want. You should be left with just the subset of boxes you want to keep. **One more useful reference**: * [tf.boolean mask](https://www.tensorflow.org/api_docs/python/tf/boolean_mask) **And one more helpful hint**: :) * For the `tf.boolean_mask`, you can keep the default `axis=None`.
# GRADED FUNCTION: yolo_filter_boxes def yolo_filter_boxes(boxes, box_confidence, box_class_probs, threshold = 0.6): """Filters YOLO boxes by thresholding on object and class confidence. Arguments: boxes -- tensor of shape (19, 19, 5, 4) box_confidence -- tensor of shape (19, 19, 5, 1) box_class_probs -- tensor of shape (19, 19, 5, 80) threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box Returns: scores -- tensor of shape (None,), containing the class probability score for selected boxes boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes Note: "None" is here because you don't know the exact number of selected boxes, as it depends on the threshold. For example, the actual output size of scores would be (10,) if there are 10 boxes. """ x = 10 y = tf.constant(100) # YOUR CODE STARTS HERE # Step 1: Compute box scores ##(≈ 1 line) box_scores = box_class_probs*box_confidence # Step 2: Find the box_classes using the max box_scores, keep track of the corresponding score ##(≈ 2 lines) box_classes = tf.math.argmax(box_scores,axis=-1) box_class_scores = tf.math.reduce_max(box_scores,axis=-1) # Step 3: Create a filtering mask based on "box_class_scores" by using "threshold". The mask should have the # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold) ## (≈ 1 line) filtering_mask = (box_class_scores >= threshold) # Step 4: Apply the mask to box_class_scores, boxes and box_classes ## (≈ 3 lines) scores = tf.boolean_mask(box_class_scores,filtering_mask) boxes = tf.boolean_mask(boxes,filtering_mask) classes = tf.boolean_mask(box_classes,filtering_mask) # YOUR CODE ENDS HERE return scores, boxes, classes tf.random.set_seed(10) box_confidence = tf.random.normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1) boxes = tf.random.normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1) box_class_probs = tf.random.normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1) scores, boxes, classes = yolo_filter_boxes(boxes, box_confidence, box_class_probs, threshold = 0.5) print("scores[2] = " + str(scores[2].numpy())) print("boxes[2] = " + str(boxes[2].numpy())) print("classes[2] = " + str(classes[2].numpy())) print("scores.shape = " + str(scores.shape)) print("boxes.shape = " + str(boxes.shape)) print("classes.shape = " + str(classes.shape)) assert type(scores) == EagerTensor, "Use tensorflow functions" assert type(boxes) == EagerTensor, "Use tensorflow functions" assert type(classes) == EagerTensor, "Use tensorflow functions" assert scores.shape == (1789,), "Wrong shape in scores" assert boxes.shape == (1789, 4), "Wrong shape in boxes" assert classes.shape == (1789,), "Wrong shape in classes" assert np.isclose(scores[2].numpy(), 9.270486), "Values are wrong on scores" assert np.allclose(boxes[2].numpy(), [4.6399336, 3.2303846, 4.431282, -2.202031]), "Values are wrong on boxes" assert classes[2].numpy() == 8, "Values are wrong on classes" print("\033[92m All tests passed!")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
**Expected Output**: scores[2] 9.270486 boxes[2] [ 4.6399336 3.2303846 4.431282 -2.202031 ] classes[2] 8 scores.shape (1789,) boxes.shape (1789, 4) classes.shape (1789,) **Note** In the test for `yolo_filter_boxes`, you're using random numbers to test the function. In real data, the `box_class_probs` would contain non-zero values between 0 and 1 for the probabilities. The box coordinates in `boxes` would also be chosen so that lengths and heights are non-negative. 2.3 - Non-max SuppressionEven after filtering by thresholding over the class scores, you still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS). Figure 7 : In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probability) of the 3 boxes. Non-max suppression uses the very important function called **"Intersection over Union"**, or IoU. Figure 8 : Definition of "Intersection over Union". Exercise 2 - iouImplement `iou()` Some hints:- This code uses the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (1,1) is the lower-right corner. In other words, the (0,0) origin starts at the top left corner of the image. As x increases, you move to the right. As y increases, you move down.- For this exercise, a box is defined using its two corners: upper left $(x_1, y_1)$ and lower right $(x_2,y_2)$, instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection.- To calculate the area of a rectangle, multiply its height $(y_2 - y_1)$ by its width $(x_2 - x_1)$. Since $(x_1,y_1)$ is the top left and $x_2,y_2$ are the bottom right, these differences should be non-negative.- To find the **intersection** of the two boxes $(xi_{1}, yi_{1}, xi_{2}, yi_{2})$: - Feel free to draw some examples on paper to clarify this conceptually. - The top left corner of the intersection $(xi_{1}, yi_{1})$ is found by comparing the top left corners $(x_1, y_1)$ of the two boxes and finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom. - The bottom right corner of the intersection $(xi_{2}, yi_{2})$ is found by comparing the bottom right corners $(x_2,y_2)$ of the two boxes and finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top. - The two boxes **may have no intersection**. You can detect this if the intersection coordinates you calculate end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculate the height $(y_2 - y_1)$ or width $(x_2 - x_1)$ and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero). - The two boxes may intersect at the **edges or vertices**, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero.**Additional Hints**- `xi1` = **max**imum of the x1 coordinates of the two boxes- `yi1` = **max**imum of the y1 coordinates of the two boxes- `xi2` = **min**imum of the x2 coordinates of the two boxes- `yi2` = **min**imum of the y2 coordinates of the two boxes- `inter_area` = You can use `max(height, 0)` and `max(width, 0)`
######################################################################### ######################## USELESS BELOW ################################## ######################################################################### # GRADED FUNCTION: iou def iou(box1, box2): """Implement the intersection over union (IoU) between box1 and box2      Arguments: box1 -- first box, list object with coordinates (box1_x1, box1_y1, box1_x2, box_1_y2)     box2 -- second box, list object with coordinates (box2_x1, box2_y1, box2_x2, box2_y2)     """ (box1_x1, box1_y1, box1_x2, box1_y2) = box1 (box2_x1, box2_y1, box2_x2, box2_y2) = box2 # YOUR CODE STARTS HERE # Calculate the (yi1, xi1, yi2, xi2) coordinates of the intersection of box1 and box2. Calculate its Area. ##(≈ 7 lines) xi1 = max(box1_x1,box2_x1) yi1 = max(box1_y1,box2_y1) xi2 = min(box1_x2,box2_x2) yi2 = min(box1_y2,box2_y2) inter_width = max(0,yi2 - yi1) inter_height = max(0,xi2 - xi1) inter_area = inter_width*inter_height # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B) ## (≈ 3 lines) box1_area = (box1_x2-box1_x1)*((box1_y2-box1_y1)) box2_area = (box2_x2-box2_x1)*((box2_y2-box2_y1)) union_area = box1_area + box2_area - inter_area # compute the IoU ## (≈ 1 line) iou = inter_area/union_area # YOUR CODE ENDS HERE return iou ## Test case 1: boxes intersect box1 = (2, 1, 4, 3) box2 = (1, 2, 3, 4) print("iou for intersecting boxes = " + str(iou(box1, box2))) assert iou(box1, box2) < 1, "The intersection area must be always smaller or equal than the union area." assert np.isclose(iou(box1, box2), 0.14285714), "Wrong value. Check your implementation. Problem with intersecting boxes" ## Test case 2: boxes do not intersect box1 = (1,2,3,4) box2 = (5,6,7,8) print("iou for non-intersecting boxes = " + str(iou(box1,box2))) assert iou(box1, box2) == 0, "Intersection must be 0" ## Test case 3: boxes intersect at vertices only box1 = (1,1,2,2) box2 = (2,2,3,3) print("iou for boxes that only touch at vertices = " + str(iou(box1,box2))) assert iou(box1, box2) == 0, "Intersection at vertices must be 0" ## Test case 4: boxes intersect at edge only box1 = (1,1,3,3) box2 = (2,3,3,4) print("iou for boxes that only touch at edges = " + str(iou(box1,box2))) assert iou(box1, box2) == 0, "Intersection at edges must be 0" print("\033[92m All tests passed!")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
**Expected Output**:```iou for intersecting boxes = 0.14285714285714285iou for non-intersecting boxes = 0.0iou for boxes that only touch at vertices = 0.0iou for boxes that only touch at edges = 0.0``` 2.4 - YOLO Non-max SuppressionYou are now ready to implement non-max suppression. The key steps are: 1. Select the box that has the highest score.2. Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= `iou_threshold`).3. Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.This will remove all boxes that have a large overlap with the selected boxes. Only the "best" boxes remain. Exercise 3 - yolo_non_max_suppressionImplement `yolo_non_max_suppression()` using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your `iou()` implementation):**Reference documentation**: - [tf.image.non_max_suppression()](https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression)```tf.image.non_max_suppression( boxes, scores, max_output_size, iou_threshold=0.5, name=None)```Note that in the version of TensorFlow used here, there is no parameter `score_threshold` (it's shown in the documentation for the latest version) so trying to set this value will result in an error message: *got an unexpected keyword argument `score_threshold`.*- [tf.gather()](https://www.tensorflow.org/api_docs/python/tf/gather)```keras.gather( reference, indices)```
# GRADED FUNCTION: yolo_non_max_suppression def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5): """ Applies Non-max suppression (NMS) to set of boxes Arguments: scores -- tensor of shape (None,), output of yolo_filter_boxes() boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later) classes -- tensor of shape (None,), output of yolo_filter_boxes() max_boxes -- integer, maximum number of predicted boxes you'd like iou_threshold -- real value, "intersection over union" threshold used for NMS filtering Returns: scores -- tensor of shape (, None), predicted score for each box boxes -- tensor of shape (4, None), predicted box coordinates classes -- tensor of shape (, None), predicted class for each box Note: The "None" dimension of the output tensors has obviously to be less than max_boxes. Note also that this function will transpose the shapes of scores, boxes, classes. This is made for convenience. """ max_boxes_tensor = tf.Variable(max_boxes, dtype='int32') # tensor to be used in tf.image.non_max_suppression() # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep ##(≈ 1 line) nms_indices = tf.image.non_max_suppression(boxes,scores,max_boxes_tensor,iou_threshold) # Use tf.gather() to select only nms_indices from scores, boxes and classes ##(≈ 3 lines) scores = tf.gather(scores,nms_indices) boxes = tf.gather(boxes,nms_indices) classes = tf.gather(classes,nms_indices) # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE return scores, boxes, classes tf.random.set_seed(10) scores = tf.random.normal([54,], mean=1, stddev=4, seed = 1) boxes = tf.random.normal([54, 4], mean=1, stddev=4, seed = 1) classes = tf.random.normal([54,], mean=1, stddev=4, seed = 1) scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes) assert type(scores) == EagerTensor, "Use tensoflow functions" print("scores[2] = " + str(scores[2].numpy())) print("boxes[2] = " + str(boxes[2].numpy())) print("classes[2] = " + str(classes[2].numpy())) print("scores.shape = " + str(scores.numpy().shape)) print("boxes.shape = " + str(boxes.numpy().shape)) print("classes.shape = " + str(classes.numpy().shape)) assert type(scores) == EagerTensor, "Use tensoflow functions" assert type(boxes) == EagerTensor, "Use tensoflow functions" assert type(classes) == EagerTensor, "Use tensoflow functions" assert scores.shape == (10,), "Wrong shape" assert boxes.shape == (10, 4), "Wrong shape" assert classes.shape == (10,), "Wrong shape" assert np.isclose(scores[2].numpy(), 8.147684), "Wrong value on scores" assert np.allclose(boxes[2].numpy(), [ 6.0797963, 3.743308, 1.3914018, -0.34089637]), "Wrong value on boxes" assert np.isclose(classes[2].numpy(), 1.7079165), "Wrong value on classes" print("\033[92m All tests passed!")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
**Expected Output**: scores[2] 8.147684 boxes[2] [ 6.0797963 3.743308 1.3914018 -0.34089637] classes[2] 1.7079165 scores.shape (10,) boxes.shape (10, 4) classes.shape (10,) 2.5 - Wrapping Up the FilteringIt's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented. Exercise 4 - yolo_evalImplement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which are provided): ```pythonboxes = yolo_boxes_to_corners(box_xy, box_wh) ```which converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of `yolo_filter_boxes````pythonboxes = scale_boxes(boxes, image_shape)```YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image -- for example, the car detection dataset had 720x1280 images -- this step rescales the boxes so that they can be plotted on top of the original 720x1280 image. Don't worry about these two functions; you'll see where they need to be called below.
def yolo_boxes_to_corners(box_xy, box_wh): """Convert YOLO box predictions to bounding box corners.""" box_mins = box_xy - (box_wh / 2.) box_maxes = box_xy + (box_wh / 2.) return tf.keras.backend.concatenate([ box_mins[..., 1:2], # y_min box_mins[..., 0:1], # x_min box_maxes[..., 1:2], # y_max box_maxes[..., 0:1] # x_max ]) # GRADED FUNCTION: yolo_eval def yolo_eval(yolo_outputs, image_shape = (720, 1280), max_boxes=10, score_threshold=.6, iou_threshold=.5): """ Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Arguments: yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors: box_xy: tensor of shape (None, 19, 19, 5, 2) box_wh: tensor of shape (None, 19, 19, 5, 2) box_confidence: tensor of shape (None, 19, 19, 5, 1) box_class_probs: tensor of shape (None, 19, 19, 5, 80) image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype) max_boxes -- integer, maximum number of predicted boxes you'd like score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box iou_threshold -- real value, "intersection over union" threshold used for NMS filtering Returns: scores -- tensor of shape (None, ), predicted score for each box boxes -- tensor of shape (None, 4), predicted box coordinates classes -- tensor of shape (None,), predicted class for each box """ # Retrieve outputs of the YOLO model (≈1 line) box_xy, box_wh, box_confidence, box_class_probs = yolo_outputs # Convert boxes to be ready for filtering functions (convert boxes box_xy and box_wh to corner coordinates) boxes = yolo_boxes_to_corners(box_xy, box_wh) # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line) scores, boxes, classes = yolo_filter_boxes(boxes, box_confidence, box_class_probs, score_threshold) # Scale boxes back to original image shape (720, 1280 or whatever) boxes = scale_boxes(boxes, image_shape) # Network was trained to run on 608x608 images # Use one of the functions you've implemented to perform Non-max suppression with # maximum number of boxes set to max_boxes and a threshold of iou_threshold (≈1 line) scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes, iou_threshold) # YOUR CODE STARTS HERE # YOUR CODE ENDS HERE return scores, boxes, classes tf.random.set_seed(10) yolo_outputs = (tf.random.normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1), tf.random.normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1), tf.random.normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1), tf.random.normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)) scores, boxes, classes = yolo_eval(yolo_outputs) print("scores[2] = " + str(scores[2].numpy())) print("boxes[2] = " + str(boxes[2].numpy())) print("classes[2] = " + str(classes[2].numpy())) print("scores.shape = " + str(scores.numpy().shape)) print("boxes.shape = " + str(boxes.numpy().shape)) print("classes.shape = " + str(classes.numpy().shape)) assert type(scores) == EagerTensor, "Use tensoflow functions" assert type(boxes) == EagerTensor, "Use tensoflow functions" assert type(classes) == EagerTensor, "Use tensoflow functions" assert scores.shape == (10,), "Wrong shape" assert boxes.shape == (10, 4), "Wrong shape" assert classes.shape == (10,), "Wrong shape" assert np.isclose(scores[2].numpy(), 171.60194), "Wrong value on scores" assert np.allclose(boxes[2].numpy(), [-1240.3483, -3212.5881, -645.78, 2024.3052]), "Wrong value on boxes" assert np.isclose(classes[2].numpy(), 16), "Wrong value on classes" print("\033[92m All tests passed!")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
**Expected Output**: scores[2] 171.60194 boxes[2] [-1240.3483 -3212.5881 -645.78 2024.3052] classes[2] 16 scores.shape (10,) boxes.shape (10, 4) classes.shape (10,) 3 - Test YOLO Pre-trained Model on ImagesIn this section, you are going to use a pre-trained model and test it on the car detection dataset. 3.1 - Defining Classes, Anchors and Image ShapeYou're trying to detect 80 classes, and are using 5 anchor boxes. The information on the 80 classes and 5 boxes is gathered in two files: "coco_classes.txt" and "yolo_anchors.txt". You'll read class names and anchors from text files. The car detection dataset has 720x1280 images, which are pre-processed into 608x608 images.
class_names = read_classes("model_data/coco_classes.txt") anchors = read_anchors("model_data/yolo_anchors.txt") model_image_size = (608, 608) # Same as yolo_model input layer size
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
3.2 - Loading a Pre-trained ModelTraining a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. You are going to load an existing pre-trained Keras YOLO model stored in "yolo.h5". These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the "YOLOv2" model, but are simply referred to as "YOLO" in this notebook.Run the cell below to load the model from this file.
yolo_model = load_model("model_data/", compile=False)
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains:
yolo_model.summary()
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do -- this is fine!**Reminder**: This model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2). 3.3 - Convert Output of the Model to Usable Bounding Box TensorsThe output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. You will need to call `yolo_head` to format the encoding of the model you got from `yolo_model` into something decipherable:`yolo_model_outputs = yolo_model(image_data)``yolo_outputs = yolo_head(yolo_model_outputs, anchors, len(class_names))`The variable `yolo_outputs` will be defined as a set of 4 tensors that you can then use as input by your yolo_eval function. If you are curious about how yolo_head is implemented, you can find the function definition in the file `keras_yolo.py`. The file is also located in your workspace in this path: `yad2k/models/keras_yolo.py`. 3.4 - Filtering Boxes`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. To perform filtering and select only the best boxes, you will call `yolo_eval`, which you had previously implemented, to do so: out_scores, out_boxes, out_classes = yolo_eval(yolo_outputs, [image.size[1], image.size[0]], 10, 0.3, 0.5) 3.5 - Run the YOLO on an ImageLet the fun begin! You will create a graph that can be summarized as follows:`yolo_model.input` is given to `yolo_model`. The model is used to compute the output `yolo_model.output``yolo_model.output` is processed by `yolo_head`. It gives you `yolo_outputs``yolo_outputs` goes through a filtering function, `yolo_eval`. It outputs your predictions: `out_scores`, `out_boxes`, `out_classes`. Now, we have implemented for you the `predict(image_file)` function, which runs the graph to test YOLO on an image to compute `out_scores`, `out_boxes`, `out_classes`.The code below also uses the following function: image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))which opens the image file and scales, reshapes and normalizes the image. It returns the outputs: image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it. image_data: a numpy-array representing the image. This will be the input to the CNN.
def predict(image_file): """ Runs the graph to predict boxes for "image_file". Prints and plots the predictions. Arguments: image_file -- name of an image stored in the "images" folder. Returns: out_scores -- tensor of shape (None, ), scores of the predicted boxes out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes out_classes -- tensor of shape (None, ), class index of the predicted boxes Note: "None" actually represents the number of predicted boxes, it varies between 0 and max_boxes. """ # Preprocess your image image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608)) yolo_model_outputs = yolo_model(image_data) # It's output is of shape (m, 19, 19, 5, 85) # But yolo_eval takes input a tensor contains 4 tensors: box_xy,box_wh, box_confidence & box_class_probs yolo_outputs = yolo_head(yolo_model_outputs, anchors, len(class_names)) out_scores, out_boxes, out_classes = yolo_eval(yolo_outputs, [image.size[1], image.size[0]], 10, 0.3, 0.5) # Print predictions info print('Found {} boxes for {}'.format(len(out_boxes), "images/" + image_file)) # Generate colors for drawing bounding boxes. colors = get_colors_for_classes(len(class_names)) # Draw bounding boxes on the image file #draw_boxes2(image, out_scores, out_boxes, out_classes, class_names, colors, image_shape) draw_boxes(image, out_boxes, out_classes, class_names, out_scores) # Save the predicted bounding box on the image image.save(os.path.join("out", str(image_file).split('.')[0]+"_annotated." +str(image_file).split('.')[1] ), quality=100) # Display the results in the notebook output_image = Image.open(os.path.join("out", str(image_file).split('.')[0]+"_annotated." +str(image_file).split('.')[1] )) imshow(output_image) return out_scores, out_boxes, out_classes
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
Run the following cell on the "test.jpg" image to verify that your function is correct.
out_scores, out_boxes, out_classes = predict("0001.jpg")
_____no_output_____
Apache-2.0
Convolutional Neural Networks/week3/1 Car_detection (Autonomous_driving)/Autonomous_driving_application_Car_detection.ipynb
nirav8403/Deep-Learning-Specialization-Coursera
Copyright 2018 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs
Eager execution basics View on TensorFlow.org Run in Google Colab View source on GitHub This is an introductory TensorFlow tutorial shows how to:* Import the required package* Create and use tensors* Use GPU acceleration* Demonstrate `tf.data.Dataset`
!pip install tf-nightly-2.0-preview
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs
Import TensorFlowImport the `tensorflow` module to get started. [Eager execution](../../guide/eager.ipynb) is enabled by default.
import tensorflow as tf
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs
TensorsA Tensor is a multi-dimensional array. Similar to NumPy `ndarray` objects, `tf.Tensor` objects have a data type and a shape. Additionally, `tf.Tensor`s can reside in accelerator memory (like a GPU). TensorFlow offers a rich library of operations ([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/matmul), [tf.linalg.inv](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) etc.) that consume and produce `tf.Tensor`s. These operations automatically convert native Python types, for example:
print(tf.add(1, 2)) print(tf.add([1, 2], [3, 4])) print(tf.square(5)) print(tf.reduce_sum([1, 2, 3])) print(tf.io.encode_base64("hello world")) # Operator overloading is also supported print(tf.square(2) + tf.square(3))
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs
Each `tf.Tensor` has a shape and a datatype:
x = tf.matmul([[1]], [[2, 3]]) print(x.shape) print(x.dtype)
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs
The most obvious differences between NumPy arrays and `tf.Tensor`s are:1. Tensors can be backed by accelerator memory (like GPU, TPU).2. Tensors are immutable. NumPy CompatibilityConverting between a TensorFlow `tf.Tensor`s and a NumPy `ndarray` is easy:* TensorFlow operations automatically convert NumPy ndarrays to Tensors.* NumPy operations automatically convert Tensors to NumPy ndarrays.Tensors are explicitly converted to NumPy ndarrays using their `.numpy()` method. These conversions are typically cheap since the array and `tf.Tensor` share the underlying memory representation, if possible. However, sharing the underlying representation isn't always possible since the `tf.Tensor` may be hosted in GPU memory while NumPy arrays are always backed by host memory, and the conversion involves a copy from GPU to host memory.
import numpy as np ndarray = np.ones([3, 3]) print("TensorFlow operations convert numpy arrays to Tensors automatically") tensor = tf.multiply(ndarray, 42) print(tensor) print("And NumPy operations convert Tensors to numpy arrays automatically") print(np.add(tensor, 1)) print("The .numpy() method explicitly converts a Tensor to a numpy array") print(tensor.numpy())
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs