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\EXPERI...
_____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`quic...
# 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 t...
_____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`_...
# 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='samp...
_____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 c...
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-so...
_____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='pi...
_____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.i...
_____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-...
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', ...
_____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 = ...
_____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 co...
_____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-...
_____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...
_____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 segm...
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 ...
_____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.ch...
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") ...
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 p...
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, ...
_____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-de...
# 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 p...
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 tknz...
_____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...
# 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 t...
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 i...
# 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(...
_____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 freque...
# 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_vecto...
_____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['Phr...
_____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 ...
! 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 =...
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 ...
#@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 genera...
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 produc...
_____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/...
#@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_sampl...
_____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 ...
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 va...
_____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 boots...
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...
_____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 ...
_____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 ...
#@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....
_____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) war...
_____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...
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}...
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 BertForS...
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, ...
/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"] =...
_____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...
_____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 ...
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].axi...
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...
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_col...
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....
_____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 conv...
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 - Convoluti...
# 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 -- i...
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.6...
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 d...
# 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 ...
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...
# 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 arra...
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 poolin...
# 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" mod...
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]]...
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...
# 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("mo...
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]...
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.1414147...
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...
_____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 i...
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. """ # (≈...
_____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 compu...
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 dis...
_____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 ag...
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 h...
_____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...
%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): ...
_____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...
# 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/Seg...
_____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 ...
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) ...
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 t...
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-darkgri...
_____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 inne...
_____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,...
_____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/', **...
_____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) retur...
_____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): ...
_____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 Farhad...
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....
_____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 aroun...
# 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) ...
_____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 sc...
######################################################################### ######################## USELESS BELOW ################################## ######################################################################### # GRADED FUNCTION: iou def iou(box1, box2): """Implement the intersection over union (IoU) be...
_____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 bo...
# 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 (Non...
_____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 ...
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[....
_____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 ...
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 we...
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 ...
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 -- tens...
_____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...
_____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....
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 T...
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 conver...
_____no_output_____
Apache-2.0
site/en/r2/tutorials/eager/eager_basics.ipynb
SamuelMarks/tensorflow-docs