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
VisualizingIf you're in a Jupyter notebook, use displacy.render .Otherwise, use displacy.serve to start a web server andshow the visualization in your browser.
from IPython.display import display, SVG from spacy import displacy
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Visualize dependencies
doc = nlp("This is a sentence") diagram = displacy.render(doc, style="dep") display(SVG(diagram))
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Visualize named entities
doc = nlp("Larry Page founded Google") diagram = displacy.render(doc, style="ent") display(SVG(diagram))
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Word vectors and similarityTo use word vectors, you need to install the larger modelsending in `md` or `lg` , for example `en_core_web_lg` . Comparing similarity
doc1 = nlp("I like cats") doc2 = nlp("I like dogs") # Compare 2 documents print(doc1.similarity(doc2)) # Compare 2 tokens print(doc1[2].similarity(doc2[2])) # Compare tokens and spans print(doc1[0].similarity(doc2[1:3]))
0.9133257426978459 0.7518883 0.19759766442466106
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Accessing word vectors
# Vector as a numpy array doc = nlp("I like cats") print(doc[2].vector.shape) # The L2 norm of the token's vector print(doc[2].vector_norm)
(384,) 24.809391
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Pipeline componentsFunctions that take a `Doc` object, modify it and return it. `Text` --> | `tokenizer`, `tagger`, `parser`, `ner`, ... | --> `Doc` Pipeline information
nlp = spacy.load("en_core_web_sm") print(nlp.pipe_names) print(nlp.pipeline)
['tagger', 'parser', 'ner'] [('tagger', <spacy.pipeline.Tagger object at 0x7f7972874ef0>), ('parser', <spacy.pipeline.DependencyParser object at 0x7f79728cb150>), ('ner', <spacy.pipeline.EntityRecognizer object at 0x7f797282c4c0>)]
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Custom components
# Function that modifies the doc and returns it def custom_component(doc): print("Do something to the doc here!") return doc # Add the component first in the pipeline nlp.add_pipe(custom_component, first=True)
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Components can be added `first` , `last` (default), or `before` or `after` an existing component. Extension attributesCustom attributes that are registered on the global `Doc` , `Token` and `Span` classes and become available as `.[link text](https://)_`
import os os._exit(00) from spacy.tokens import Doc, Token, Span import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("The sky over New York is blue")
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Attribute extensions *WITH DEFAULT VALUE*
# Register custom attribute on Token class Token.set_extension("is_color", default=False) # Overwrite extension attribute with default value doc[6]._.is_color = True
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Property extensions *WITH GETTER & SETTER*
# Register custom attribute on Doc class get_reversed = lambda doc: doc.text[::-1] Doc.set_extension("reversed", getter=get_reversed) # Compute value of extension attribute with getter doc._.reversed
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Method extensions *CALLABLE METHOD*
# Register custom attribute on Span class has_label = lambda span, label: span.label_ == label Span.set_extension("has_label", method=has_label) # Compute value of extension attribute with method doc[3:5]._.has_label("GPE")
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Rule-based matching Using the matcher
# Matcher is initialized with the shared vocab from spacy.matcher import Matcher # Each dict represents one token and its attributes matcher = Matcher(nlp.vocab) # Add with ID, optional callback and pattern(s) pattern = [{"LOWER": "new"}, {"LOWER": "york"}] matcher.add("CITIES", None, pattern) # Match by calling the...
New York
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Rule-based matching Token patterns
# "love cats", "loving cats", "loved cats" pattern1 = [{"LEMMA": "love"}, {"LOWER": "cats"}] # "10 people", "twenty people" pattern2 = [{"LIKE_NUM": True}, {"TEXT": "people"}] # "book", "a cat", "the sea" (noun + optional article) pattern3 = [{"POS": "DET", "OP": "?"}, {"POS": "NOUN"}]
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Operators and quantifiers Can be added to a token dict as the `"OP"` key* `!` Negate pattern and match **exactly 0 times**.* `?` Make pattern optional and match **0 or 1 times**.* `+` Require pattern to match **1 or more times**.* `*` Allow pattern to match **0 or more times**. Glossary| | ||---|---|| Tokenizati...
_____no_output_____
MIT
notebook.ipynb
abhiWriteCode/Tutorial-for-spaCy
Make gifIn this example, we load in a single subject example, remove electrodes that exceeda kurtosis threshold (in place), load a model, and predict activity at allmodel locations. We then convert the reconstruction to a nifti and plot 3 consecutive timepointsfirst with the plot_glass_brain and then create .png file...
# Code source: Lucy Owen & Andrew Heusser # License: MIT # load import supereeg as se # load example data bo = se.load('example_data') # load example model model = se.load('example_model') # the default will replace the electrode location with the nearest voxel and reconstruct at all other locations reconstructed_b...
_____no_output_____
MIT
docs/auto_examples/make_gif.ipynb
tmuntianu/supereeg
"Loss Functions: Cross Entropy Loss and You!"> "Meet multi-classification's favorite loss function"- toc: true - badges: true- comments: true- author: Wayde Gilliam- image: images/articles/understanding-cross-entropy-loss-logo.png
# only run this cell if you are in collab !pip install fastai import torch from torch.nn import functional as F from fastai2.vision.all import *
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
We've been doing multi-classification since week one, and last week, we learned about how a NN "learns" by evaluating its predictions as measured by something called a "loss function." So for multi-classification tasks, what is our loss function?
path = untar_data(URLs.PETS)/'images' def is_cat(x): return x[0].isupper() dls = ImageDataLoaders.from_name_func( path, get_image_files(path), valid_pct=0.2, seed=42, label_func=is_cat, item_tfms=Resize(224)) learn = cnn_learner(dls, resnet34, metrics=error_rate) learn.loss_func
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
Negative Log-Likelihood & CrossEntropy LossTo understand `CrossEntropyLoss`, we need to first understand something called `Negative Log-Likelihood` Negative Log-Likelihood (NLL) Loss Let's imagine a model who's objective is to predict the label of an example given five possible classes to choose from. Our prediction...
preds = torch.randn(3, 5); preds
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
Because this is a supervised task, we know the actual labels of our three training examples above (e.g., the label of the first example is the first class, the label of the 2nd example the 4th class, and so forth)
targets = torch.tensor([0, 3, 4])
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
**Step 1**: Convert the predictions for each example into probabilities using `softmax`. This describes how confident your model is in predicting what it belongs to respectively for each class
probs = F.softmax(preds, dim=1); probs
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
If we sum the probabilities across each example, you'll see they add up to 1
probs.sum(dim=1)
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
**Step 2**: Calculate the "negative log likelihood" for each example where `y` = the probability of the correct class`loss = -log(y)`We can do this in one-line using something called ***tensor/array indexing***
example_idxs = range(len(preds)); example_idxs correct_class_probs = probs[example_idxs, targets]; correct_class_probs nll = -torch.log(correct_class_probs); nll
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
**Step 3**: The loss is the mean of the individual NLLs
nll.mean()
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
... or using PyTorch
F.nll_loss(torch.log(probs), targets)
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
Cross Entropy Loss ... or we can do this all at once using PyTorch's `CrossEntropyLoss`
F.cross_entropy(preds, targets)
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
As you can see, cross entropy loss simply combines the `log_softmax` operation with the `negative log-likelihood` loss So why not use accuracy?
# this function is actually copied verbatim from the utils package in fastbook (see footnote 1) def plot_function(f, tx=None, ty=None, title=None, min=-2, max=2, figsize=(6,4)): x = torch.linspace(min,max) fig,ax = plt.subplots(figsize=figsize) ax.plot(x,f(x)) if tx is not None: ax.set_xlabel(tx) if...
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
NLL loss will be higher the smaller the probability *of the correct class***What does this all mean?** The lower the confidence it has in predicting the correct class, the higher the loss. It will:1) Penalize correct predictions that it isn't confident about more so than correct predictions it is very confident about.2...
_____no_output_____
Apache-2.0
_notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb
XCS224U-Spring2021-TeamTextSumm/ohmeow_website
- A stationary time series is one whose statistical properties such as mean, variance, autocorrelation, etc. are all constant over time. Most statistical forecasting methods are based on the assumption that the time series can be rendered approximately stationary (i.e., "stationarized") through the use of mathematical ...
from statsmodels.tsa.stattools import adfuller def test_stationary(timeseries): #Determing rolling statistics moving_average=timeseries.rolling(window=12).mean() standard_deviation=timeseries.rolling(window=12).std() #Plot rolling statistics: plt.plot(timeseries,color='blue',label="Origina...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- There are 2 major reasons behind non-stationaruty of a TS:- - Trend – varying mean over time. For eg, in this case we saw that on average, the number of passengers was growing over time.- - Seasonality – variations at specific time-frames. eg people might have a tendency to buy cars in a particular month because of p...
indexedDataset_logscale=np.log(indexedDataset) test_stationary(indexedDataset_logscale)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Dataset Log Minus Moving Average (dl_ma)
rolmeanlog=indexedDataset_logscale.rolling(window=12).mean() dl_ma=indexedDataset_logscale-rolmeanlog dl_ma.head(12) dl_ma.dropna(inplace=True) dl_ma.head(12) test_stationary(dl_ma)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Exponential Decay Weighted Average (edwa)
edwa=indexedDataset_logscale.ewm(halflife=12,min_periods=0,adjust=True).mean() plt.plot(indexedDataset_logscale) plt.plot(edwa,color='red')
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Dataset Logscale Minus Moving Exponential Decay Average (dlmeda)
dlmeda=indexedDataset_logscale-edwa test_stationary(dlmeda)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Eliminating Trend and Seasonality - Differencing – taking the differece with a particular time lag- Decomposition – modeling both trend and seasonality and removing them from the model. Differencing Dataset Log Div Shifting (dlds)
#Before Shifting indexedDataset_logscale.head() #After Shifting indexedDataset_logscale.shift().head() dlds=indexedDataset_logscale-indexedDataset_logscale.shift() dlds.dropna(inplace=True) test_stationary(dlds)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Decomposition
from statsmodels.tsa.seasonal import seasonal_decompose decompostion= seasonal_decompose(indexedDataset_logscale,freq=10) trend=decompostion.trend seasonal=decompostion.seasonal residual=decompostion.resid plt.subplot(411) plt.plot(indexedDataset_logscale,label='Original') plt.legend(loc='best') plt.subplot(412) plt...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- Here trend, seasonality are separated out from data and we can model the residuals. Lets check stationarity of residuals:
decomposedlogdata=residual decomposedlogdata.dropna(inplace=True) test_stationary(decomposedlogdata)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Forecasting a Time Series - ARIMA stands for Auto-Regressive Integrated Moving Averages. The ARIMA forecasting for a stationary time series is nothing but a linear (like a linear regression) equation. The predictors depend on the parameters (p,d,q) of the ARIMA model:- - Number of AR (Auto-Regressive) terms (p): AR te...
from statsmodels.tsa.stattools import acf,pacf lag_acf=acf(dlds,nlags=20) lag_pacf=pacf(dlds,nlags=20,method='ols') plt.subplot(121) plt.plot(lag_acf) plt.axhline(y=0, linestyle='--',color='gray') plt.axhline(y=1.96/np.sqrt(len(dlds)),linestyle='--',color='gray') plt.axhline(y=-1.96/np.sqrt(len(dlds)),linestyle='--',c...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- In this plot, the two dotted lines on either sides of 0 are the confidence interevals. These can be used to determine the ‘p’ and ‘q’ values as:- - p – The lag value where the PACF chart crosses the upper confidence interval for the first time. If we notice closely, in this case p=2.- - q – The lag value where the AC...
from statsmodels.tsa.arima_model import ARIMA model=ARIMA(indexedDataset_logscale,order=(5,1,0)) results_AR=model.fit(disp=-1) plt.plot(dlds) plt.plot(results_AR.fittedvalues,color='red') plt.title('RSS: %.4f'%sum((results_AR.fittedvalues-dlds['MONSOON'])**2)) print('Plotting AR Model') model = ARIMA(indexedDataset_lo...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
Taking it back to original scale from residual scale
#storing the predicted results as a separate series predictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True) predictions_ARIMA_diff.head()
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- Notice that these start from ‘1949-02-01’ and not the first month. Why? This is because we took a lag by 1 and first element doesn’t have anything before it to subtract from. The way to convert the differencing to log scale is to add these differences consecutively to the base number. An easy way to do it is to first...
#convert to cummuative sum predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum() predictions_ARIMA_diff_cumsum predictions_ARIMA_log = pd.Series(indexedDataset_logscale['MONSOON'].ix[0], index=indexedDataset_logscale.index) predictions_ARIMA_log predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_AR...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- Here the first element is base number itself and from there on the values cumulatively added.
#Last step is to take the exponent and compare with the original series. predictions_ARIMA = np.exp(predictions_ARIMA_log) plt.plot(indexedDataset) plt.plot(predictions_ARIMA) plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-indexedDataset['MONSOON'])**2)/len(indexedDataset)))
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
- Finally we have a forecast at the original scale.
results_ARIMA.plot_predict(1,26) #start = !st month #end = 10yrs forcasting = 144+12*10 = 264th month #Two models corresponds to AR & MA x=results_ARIMA.forecast(steps=5) print(x) #values in residual equivalent for i in range(0,5): print(x[0][i],end='') print('\t',x[1][i],end='') print('\t',x[2][i]) np.ex...
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb
romilshah525/SIH-2019
第10题(index=9)正确答案分布
x=[str(['02_09', '05_06']),str(['02_05', '06_09']),str(['02_06', '05_09'])] data1 = go.Bar(x = x, y = [480/662,68/662,39/662], name = 'all') data2 = go.Bar(x = x, y = [158/267,37/267,4/267], name = 'junior') data3 = go.Bar(x = x, y = [322/395,31/395,24/395], name = 'senior') layout={"title": "第10题(index=9)的正确答案分布,...
_____no_output_____
Apache-2.0
first_analysis/plot.ipynb
Brook1711/openda1
寻找第19题所有的正确答案
# 所有可能的五角星(0,a)和三角形(1,b)组合 seq_list = [] for i in range(8): for j in range(int(math.pow(2,i+1))): temp=str(bin(j))[2:].zfill(i+1).replace('0','a') temp = temp.replace('1', 'b') seq_list.append(temp) # 所有可能的长方形(1)和圆形(0)组合 trans_list = [] for i in range(3): for j in range(int(math.pow(2,i+...
_____no_output_____
Apache-2.0
first_analysis/plot.ipynb
Brook1711/openda1
Table of Contents 1&nbsp;&nbsp;Initialization1.1&nbsp;&nbsp;1 - Neural Network model1.2&nbsp;&nbsp;2 - Zero initialization1.3&nbsp;&nbsp;3 - Random initialization1.4&nbsp;&nbsp;4 - He initialization1.5&nbsp;&nbsp;5 - Conclusions InitializationWelcome to the first assignment of "Improving Deep Neural Networks". Traini...
import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec %matplotlib inline plt.rcParams['f...
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
You would like a classifier to separate the blue dots from the red dots. 1 - Neural Network model You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with: - *Zeros initialization* -- setting `initialization = "zeros"` in the input argument.- ...
def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"): """ Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID. Arguments: X -- input data, of shape (2, number of examples) Y -- true "label" vector (containing 0 ...
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
2 - Zero initializationThere are two types of parameters to initialize in a neural network:- the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$- the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$**Exercise**: Implement the following function to initialize all parameters to ...
# GRADED FUNCTION: initialize_parameters_zeros def initialize_parameters_zeros(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": ...
W1 = [[0. 0. 0.] [0. 0. 0.]] b1 = [[0.] [0.]] W2 = [[0. 0.]] b2 = [[0.]]
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
**Expected Output**: **W1** [[ 0. 0. 0.] [ 0. 0. 0.]] **b1** [[ 0.] [ 0.]] **W2** [[ 0. 0.]] **b2** [[ 0.]] Run the following code to train your model on 15,000 iterations using...
parameters = model(train_X, train_Y, initialization = "zeros") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters)
Cost after iteration 0: 0.6931471805599453 Cost after iteration 1000: 0.6931471805599453 Cost after iteration 2000: 0.6931471805599453 Cost after iteration 3000: 0.6931471805599453 Cost after iteration 4000: 0.6931471805599453 Cost after iteration 5000: 0.6931471805599453 Cost after iteration 6000: 0.6931471805599453 C...
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:
print ("predictions_train = " + str(predictions_train)) print ("predictions_test = " + str(predictions_test)) plt.title("Model with Zeros initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
The model is predicting 0 for every example. In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is no...
# GRADED FUNCTION: initialize_parameters_random def initialize_parameters_random(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": ...
W1 = [[ 17.88628473 4.36509851 0.96497468] [-18.63492703 -2.77388203 -3.54758979]] b1 = [[0.] [0.]] W2 = [[-0.82741481 -6.27000677]] b2 = [[0.]]
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
**Expected Output**: **W1** [[ 17.88628473 4.36509851 0.96497468] [-18.63492703 -2.77388203 -3.54758979]] **b1** [[ 0.] [ 0.]] **W2** [[-0.82741481 -6.27000677]] **b2** [[ 0.]] ...
parameters = model(train_X, train_Y, initialization = "random") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters)
Cost after iteration 0: inf Cost after iteration 1000: 0.6250884962121392
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
If you see "inf" as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn't worth worrying about for our purposes. Anyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no lon...
print (predictions_train) print (predictions_test) plt.title("Model with large random initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
**Observations**:- The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\log(a^{[3]}) = \log(0)$, the loss...
# GRADED FUNCTION: initialize_parameters_he def initialize_parameters_he(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- ...
W1 = [[ 1.78862847 0.43650985] [ 0.09649747 -1.8634927 ] [-0.2773882 -0.35475898] [-0.08274148 -0.62700068]] b1 = [[0.] [0.] [0.] [0.]] W2 = [[-0.03098412 -0.33744411 -0.92904268 0.62552248]] b2 = [[0.]]
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
**Expected Output**: **W1** [[ 1.78862847 0.43650985] [ 0.09649747 -1.8634927 ] [-0.2773882 -0.35475898] [-0.08274148 -0.62700068]] **b1** [[ 0.] [ 0.] [ 0.] [ 0.]] **W2** [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]...
parameters = model(train_X, train_Y, initialization = "he") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) plt.title("Model with He initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.se...
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
**Observations**:- The model with He initialization separates the blue and the red dots very well in a small number of iterations. 5 - Conclusions You have seen three different types of initializations. For the same number of iterations and same hyperparameters the comparison is: **Model** ...
%load_ext version_information %version_information numpy, matplotlib, sklearn
_____no_output_____
MIT
02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb
soltaniehha/deep-learning-specialization-coursera
3D volumetric rendering with NeRF**Authors:** [Aritra Roy Gosthipaty](https://twitter.com/arig23498), [Ritwik Raha](https://twitter.com/ritwik_raha)**Date created:** 2021/08/09**Last modified:** 2021/08/09**Description:** Minimal implementation of volumetric rendering as shown in NeRF. IntroductionIn this example, we...
# Setting random seed to obtain reproducible results. import tensorflow as tf tf.random.set_seed(42) import os import glob import imageio import numpy as np from tqdm import tqdm from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt # Initialize global variables. AUTO = tf....
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
Download and load the dataThe `npz` data file contains images, camera poses, and a focal length.The images are taken from multiple camera angles as shown in**Figure 3**.| ![camera-angles](https://i.imgur.com/FLsi2is.png) || :---: || **Figure 3**: Multiple camera angles [Source: NeRF](https://arxiv.org/abs/2003.08934) ...
# Download the data if it does not already exist. file_name = "tiny_nerf_data.npz" url = "https://people.eecs.berkeley.edu/~bmild/nerf/tiny_nerf_data.npz" if not os.path.exists(file_name): data = keras.utils.get_file(fname=file_name, origin=url) data = np.load(data) images = data["images"] im_shape = images.shape ...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
Data pipelineNow that you've understood the notion of camera matrixand the mapping from a 3D scene to 2D images,let's talk about the inverse mapping, i.e. from 2D image to the 3D scene.We'll need to talk about volumetric rendering with ray casting and tracing,which are common computer graphics techniques.This section ...
def encode_position(x): """Encodes the position into its corresponding Fourier feature. Args: x: The input coordinate. Returns: Fourier features tensors of the position. """ positions = [x] for i in range(POS_ENCODE_DIMS): for fn in [tf.sin, tf.cos]: positi...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
NeRF modelThe model is a multi-layer perceptron (MLP), with ReLU as its non-linearity.An excerpt from the paper:*"We encourage the representation to be multiview-consistent byrestricting the network to predict the volume density sigma as afunction of only the location `x`, while allowing the RGB color `c` to bepredict...
def get_nerf_model(num_layers, num_pos): """Generates the NeRF neural network. Args: num_layers: The number of MLP layers. num_pos: The number of dimensions of positional encoding. Returns: The `tf.keras` model. """ inputs = keras.Input(shape=(num_pos, 2 * 3 * POS_ENCODE_D...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
TrainingThe training step is implemented as part of a custom `keras.Model` subclassso that we can make use of the `model.fit` functionality.
class NeRF(keras.Model): def __init__(self, nerf_model): super().__init__() self.nerf_model = nerf_model def compile(self, optimizer, loss_fn): super().compile() self.optimizer = optimizer self.loss_fn = loss_fn self.loss_tracker = keras.metrics.Mean(name="loss"...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
Visualize the training stepHere we see the training step. With the decreasing loss, the renderedimage and the depth maps are getting better. In your local system, youwill see the `training.gif` file generated.![training-20](https://i.imgur.com/ql5OcYA.gif) InferenceIn this section, we ask the model to build novel vie...
# Get the trained NeRF model and infer. nerf_model = model.nerf_model test_recons_images, depth_maps = render_rgb_depth( model=nerf_model, rays_flat=test_rays_flat, t_vals=test_t_vals, rand=True, train=False, ) # Create subplots. fig, axes = plt.subplots(nrows=5, ncols=3, figsize=(10, 20)) for ax,...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
Render 3D SceneHere we will synthesize novel 3D views and stitch all of them togetherto render a video encompassing the 360-degree view.
def get_translation_t(t): """Get the translation matrix for movement in t.""" matrix = [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, t], [0, 0, 0, 1], ] return tf.convert_to_tensor(matrix, dtype=tf.float32) def get_rotation_phi(phi): """Get the rotation matrix for moveme...
_____no_output_____
Apache-2.0
examples/vision/ipynb/nerf.ipynb
k-w-w/keras-io
CellsIn this examples I'll show how to render a large number of cells in your scene. This can be useful when visualizing the results of tracking experiments after they have been aligned to the allen brain atlas reference frame. set up
# We begin by adding the current path to sys.path to make sure that the imports work correctly import sys sys.path.append('../') import os import pandas as pd from vtkplotter import * # Import variables from brainrender import * # <- these can be changed to personalize the look of your renders # Import brainrender c...
_____no_output_____
MIT
Examples/notebooks/Cells.ipynb
paulbrodersen/BrainRender
Get dataTo keep things interesting, we will generate N random "cells" in a number of regions of interest. These coordinates will then be used to render the cells. If you have your coordinates saved in a file (e.g. a .csv or .h5 or .pkl), you can use `Scene.add_cells_from_file` and skip this next step.
# Create a scene scene = Scene() # Define in which regions to crate the cells and how many regions = ["MOs", "VISp", "ZI"] N = 1000 # getting 1k cells per region, but brainrender can deal with >1M cells easily. # Render brain regions and add transparency slider. scene.add_brain_regions(regions, colors="ivory", alpha...
_____no_output_____
MIT
Examples/notebooks/Cells.ipynb
paulbrodersen/BrainRender
Load the data
STATSBOMB = os.path.join('..', '..', 'data', 'statsbomb') df_statsbomb_event = pd.read_parquet(os.path.join(STATSBOMB, 'event.parquet')) df_statsbomb_freeze = pd.read_parquet(os.path.join(STATSBOMB, 'freeze.parquet'))
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Filter shots
df_statsbomb_shot = df_statsbomb_event[df_statsbomb_event.type_name == 'Shot'].copy()
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Features based on StatsBomb freeze frame Features based on freeze frame - this takes a while as looping over 20k+ shots:- space around goaly- space around shooter- number of players in shot angle to goal Filter out penalty goals from freeze frames
non_penalty_id = df_statsbomb_shot.loc[(df_statsbomb_shot.sub_type_name != 'Penalty'), 'id'] df_statsbomb_freeze = df_statsbomb_freeze[df_statsbomb_freeze.id.isin(non_penalty_id)].copy()
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Add the shot taker to the freeze frame
cols_to_keep = ['id','player_id','player_name','position_id','position_name','x','y','match_id'] freeze_ids = df_statsbomb_freeze.id.unique() df_shot_taker = df_statsbomb_shot.loc[df_statsbomb_shot.id.isin(freeze_ids), cols_to_keep].copy() df_shot_taker['player_teammate'] = True df_shot_taker['event_freeze_id'] = 0 df_...
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Calculate features
statsbomb_pitch = Pitch() # store the results in lists area_goal = [] area_shot = [] n_angle = [] # loop through the freeze frames create a voronoi and calculate the area around the goalkeeper/ shot taker for shot_id in df_statsbomb_freeze.id.unique(): subset = df_statsbomb_freeze.loc[df_statsbomb_freeze.id == sh...
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Add on goalkeeper position
gk_position = df_statsbomb_freeze.loc[(df_statsbomb_freeze.player_position_name == 'Goalkeeper') & (df_statsbomb_freeze.player_teammate == False), ['id', 'x', 'y']] gk_position.rename({'x': 'goalkeeper_x','y': 'goalkeeper_y'}, axis=1, inplace=True) df_freeze_features = df_freeze_fe...
_____no_output_____
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Save features
df_freeze_features.to_parquet(os.path.join(STATSBOMB, 'freeze_features.parquet')) df_freeze_features.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 21536 entries, 0 to 21535 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 21536 non-null object 1 area_shot 21536 non-null float64 2 area_goal 21536 non-null float...
MIT
notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb
andrewRowlinson/expected-goals-thesis
Simple Widget Introduction What are widgets? Widgets are elements that exists in both the front-end and the back-end.![Kernel & front-end diagram](images/FrontendKernel.png) What can they be used for? You can use widgets to build **interactive GUIs** for your notebooks. You can also use widgets to **synchronize sta...
from ipywidgets import *
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
repr Widgets have their own display `repr` which allows them to be displayed using IPython's display framework. Constructing and returning an `IntSlider` automatically displays the widget (as seen below). Widgets are **displayed inside the `widget area`**, which sits between the code cell and output. **You can hide...
IntSlider(min=0, max=10)
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
display() You can also explicitly display the widget using `display(...)`.
from IPython.display import display w = IntSlider(min=0, max=10) display(w)
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Multiple display() calls If you display the same widget twice, the displayed instances in the front-end **will remain in sync** with each other.
display(w)
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Why does displaying the same widget twice work? Widgets are **represented in the back-end by a single object**. Each time a widget is displayed, **a new representation** of that same object is created in the front-end. These representations are called **views**.![Kernel & front-end diagram](images/WidgetModelView.pn...
display(w) w.close()
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Widget properties All of the IPython widgets **share a similar naming scheme**. To read the value of a widget, you can query its `value` property.
w = IntSlider(min=0, max=10) display(w) w.value
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Similarly, to set a widget's value, you can set its `value` property.
w.value = 100
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Keys In addition to `value`, most widgets share `keys`, `description`, `disabled`, and `visible`. To see the entire list of synchronized, stateful properties, of any specific widget, you can **query the `keys` property**.
w.keys
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Shorthand for setting the initial values of widget properties While creating a widget, you can set some or all of the initial values of that widget by **defining them as keyword arguments in the widget's constructor** (as seen below).
Text(value='Hello World!', disabled=True)
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Linking two similar widgets If you need to display the same value two different ways, you'll have to use two different widgets. Instead of **attempting to manually synchronize the values** of the two widgets, you can use the `traitlet` `link` function **to link two properties together**. Below, the values of three w...
from traitlets import link a = FloatText() b = FloatSlider(min=0.0, max=10.0) c = FloatProgress(min=0, max=10) display(a,b,c) blink = link((a, 'value'), (b, 'value')) clink = link((a, 'value'), (c, 'value')) a.value = 5
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Unlinking widgets Unlinking the widgets is simple. All you have to do is call `.unlink` on the link object.
clink.unlink()
_____no_output_____
Apache-2.0
intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb
cgentemann/tutorials
Import
# Matplotlib import matplotlib.pyplot as plt # Tensorflow import tensorflow as tf # Numpy and Pandas import numpy as np import pandas as pd # Ohter import import sys from sklearn.preprocessing import StandardScaler
Limited tf.compat.v2.summary API due to missing TensorBoard installation Limited tf.summary API due to missing TensorBoard installation
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Be sure to used Tensorflow 2.0
assert hasattr(tf, "function") # Be sure to use tensorflow 2.0
_____no_output_____
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Load the dataset: Fashion MNIST ![](https://storage.googleapis.com/kaggle-datasets-images/2243/3791/9384af51de8baa77f6320901f53bd26b/dataset-cover.png)
# Fashio MNIST fashion_mnist = tf.keras.datasets.fashion_mnist (images, targets), (_, _) = fashion_mnist.load_data() # Get only a subpart of the dataset # Get only a subpart images = images[:10000] targets = targets [:10000] images = images.reshape(-1, 784) images = images.astype(float) scaler = StandardScaler() image...
(10000, 784) (10000,)
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Plot one of the data
targets_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot" ] # Plot one image plt.imshow(images[10].reshape(28, 28), cmap="binary") #plt.title(targets_names[targets[10]]) plt.title(targets_names[targets[10]]) plt.show() #print("First line ...
First line of one image [-0.01426971 -0.02645579 -0.029489 -0.04635542 -0.06156617 -0.07641125 -0.10509579 -0.16410192 -0.23986957 -0.36929666 -0.57063232 -0.6909092 -0.7582382 -0.74450346 -0.17093142 0.80572169 0.60465021 0.69474334 0.01007169 -0.32085836 -0.20882718 -0.14379861 -0.11434416 -0.09302065 0.0...
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Create the model![](images/simple_nn.png) Create the model
# Flatten model = tf.keras.models.Sequential() #model.add(tf.keras.layers.Flatten(input_shape=[28, 28])) # Add the layers model.add(tf.keras.layers.Dense(256, activation="relu")) model.add(tf.keras.layers.Dense(128, activation="relu")) model.add(tf.keras.layers.Dense(10, activation="softmax")) model_output = model.pr...
[[0.17820482 0.05316375 0.07201441 0.1023543 0.02913541 0.17055362 0.06326886 0.24632096 0.02520118 0.05978273]] [9]
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Model Summary
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) multiple 200960 ____________________________________...
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Compile the model
# Compile the model model.compile( loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"] )
_____no_output_____
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Caterogical cross entropy
images_test = images[:5] labels_test = targets[:5] print(images_test.shape) print(labels_test) outputs_test = model.predict(images_test) print(outputs_test.shape) print("Output", outputs_test) #print("\nLabels", labels_test) filtered_outputs_test = outputs_test[np.arange(5), labels_test] print("\nFiltered output",...
(5, 784) [9 0 0 3 0] (5, 10) Output [[0.00155602 0.00106303 0.00698406 0.00284724 0.01145798 0.03515041 0.01286932 0.0088392 0.04853413 0.8706986 ] [0.7814132 0.00516847 0.01360413 0.0021324 0.01019276 0.00489966 0.15709291 0.00928725 0.01079097 0.00541825] [0.07476368 0.22221217 0.0560216 0.36471143 0.030126...
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
Train the model
history = model.fit(images, targets, epochs=1) loss_curve = history.history["loss"] acc_curve = history.history["accuracy"] plt.plot(loss_curve) plt.title("Loss") plt.show() plt.plot(acc_curve) plt.title("Accuracy") plt.show()
_____no_output_____
MIT
Neural Network Error-Function.ipynb
Haytam222/Neural-Network
get historical actual data
datafarm = DataFarm() historical_data = datafarm.run() week_data = historical_data.sum().sort_index() week_data = week_data # 2018年以来 没周人数 vacation_week_weight = {'201826':0.5, '201827':0.6, '201828':0.7, '201829':0.8, ...
_____no_output_____
MIT
jiuqu/student_count_predict.ipynb
LeonKennedy/jupyter_space
$y_i = c_1e^{-x_i} + c_2x_i + c_3z_i$
y = week_data.values x = np.r_[1:len(y)+1] z = whole_day_week.values # A = np.c_[np.exp(-x)[:, np.newaxis], x[:, np.newaxis], z[:, np.newaxis]] A = np.c_[x[:, np.newaxis], z[:, np.newaxis]] c, resid, rank, sigma = linalg.lstsq(A, y) xi2 = np.r_[1:len(y):10j] yi2 = c[0]*x + c[1]*z plt.figure(1, figsize=(80,30)) plt.b...
_____no_output_____
MIT
jiuqu/student_count_predict.ipynb
LeonKennedy/jupyter_space
减去寒暑假影响后 使用exponentially weighted windows
plt.figure(2, figsize=(80, 19)) base_data = week_data - c[1]*z base_data.plot(style='b--') base_data.ewm(span=5).mean().plot(style='r')
_____no_output_____
MIT
jiuqu/student_count_predict.ipynb
LeonKennedy/jupyter_space
细粒度拟合 (roomtype, chapter)
historical_data.groupby(level=[1,2]).sum()
_____no_output_____
MIT
jiuqu/student_count_predict.ipynb
LeonKennedy/jupyter_space
First Let's Get the Butler and a Tract
butler = Butler(REPOS['2.2i_dr6_wfd']) skymap = butler.get("deepCoadd_skyMap") # this list is hard coded - the gen 2 butler doesn't have a method for introspection meta = {} meta["all_tracts"] = """2723 2730 2897 2904 3076 3083 3259 3266 3445 3452 3635 3642 3830 3837 4028 4035 4230 4428 4435 4636 46...
_____no_output_____
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Make a Grid of objectsWe will use the `fsi_tools` package to make a hexagonal grid of object positions.
grid = make_hexgrid_for_tract(ti, rng=10) plt.figure() plt.plot(grid["x"], grid["y"], '.') ax = plt.gca() ax.set_aspect('equal') plt.xlim(0, 640) plt.ylim(0, 640)
_____no_output_____
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Neat! Building the Source Catalog
srcs = fitsio.read( "/global/cfs/cdirs/lsst/groups/fake-source-injection/DC2/catalogs/" "cosmoDC2_v1.1.4_small_fsi_catalog.fits", ) msk = srcs["rmagVar"] <= 25 srcs = srcs[msk] rng = np.random.RandomState(seed=10) inds = rng.choice(len(srcs), size=len(grid), replace=True) tract_sources = srcs[inds].copy() trac...
_____no_output_____
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Now Cut to Just the First Patch
patch = ti[0] # TODO: we may want to expand this box to account for nbrs light msk = patch.getOuterBBox().contains(grid["x"], grid["y"]) print("found %d objects in patch %s" % (np.sum(msk), "%d,%d" % patch.getIndex()))
found 4741 objects in patch 0,0
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Run the Stack FSI Code
fitsio.write("ssi.fits", tract_sources[msk], clobber=True) %%time !insertFakes.py \ /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/rerun/run2.2i-coadd-wfd-dr6-v1 \ --output test/ \ --id tract=4030 patch=0,0 \ filter=r -c fakeType=ssi.fits \ --clobber-config --no-versions
CameraMapper INFO: Loading exposure registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/registry.sqlite3 CameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3 CameraMapper INFO: Loading calib registry fr...
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Make an Image
butler = Butler("./test/") cutoutSize = geom.ExtentI(1001, 1001) ra = np.mean(tract_sources[msk]["raJ2000"]) / np.pi * 180.0 dec = np.mean(tract_sources[msk]["decJ2000"]) / np.pi * 180.0 point = geom.SpherePoint(ra, dec, geom.degrees) skymap = butler.get("deepCoadd_skyMap") tractInfo = skymap.findTract(point) patchIn...
{'tract': 4030, 'patch': '0,0', 'filter': 'r'}
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools