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 |
|---|---|---|---|---|---|
OptimizersWe want to update the generator and discriminator variables separately. So, we'll define two separate Adam optimizers. | import torch.optim as optim
# learning rate for optimizers
lr = 0.002
# Create optimizers for the discriminator and generator
d_optimizer = optim.Adam(D.parameters(), lr)
g_optimizer = optim.Adam(G.parameters(), lr) | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
--- TrainingTraining will involve alternating between training the discriminator and the generator. We'll use our functions `real_loss` and `fake_loss` to help us calculate the discriminator losses in all of the following cases. Discriminator training1. Compute the discriminator loss on real, training images 2. ... | import pickle as pkl
# training hyperparams
num_epochs = 100
# keep track of loss and generated, "fake" samples
samples = []
losses = []
print_every = 400
# Get some fixed data for sampling. These are images that are held
# constant throughout training, and allow us to inspect the model's performance
s... | Epoch [ 1/ 100] | d_loss: 1.3531 | g_loss: 0.7711
Epoch [ 1/ 100] | d_loss: 1.2302 | g_loss: 1.2285
Epoch [ 1/ 100] | d_loss: 1.4087 | g_loss: 1.0569
Epoch [ 2/ 100] | d_loss: 1.3109 | g_loss: 1.0101
Epoch [ 2/ 100] | d_loss: 1.2816 | g_loss: 1.0060
Epoch [ 2/ 100] | d_loss: 1.3010 | g_loss: 1.0... | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Training lossHere we'll plot the training losses for the generator and discriminator, recorded after each epoch. | fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator')
plt.plot(losses.T[1], label='Generator')
plt.title("Training Losses")
plt.legend() | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Generator samples from trainingHere we can view samples of images from the generator. First we'll look at the images we saved during training. | # helper function for viewing a list of passed in sample images
def view_samples(epoch, samples):
fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
img = img.detach()
ax.xaxis.set_visible(False)
ax.yaxi... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn't representative of the full range of images this generator can make. | # -1 indicates final epoch's samples (the last in the list)
view_samples(-1, samples) | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Below I'm showing the generated images as the network was training, every 10 epochs. | rows = 10 # split epochs into 10, so 100/10 = every 10 epochs
cols = 6
fig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)
for sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):
for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):
img = img.detach... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s. Sampling from the generatorWe can also get completely new images from the generator by using the checkpoint we saved after training. **We... | # randomly generated, new latent vectors
sample_size=16
rand_z = np.random.uniform(-1, 1, size=(sample_size, z_size))
rand_z = torch.from_numpy(rand_z).float()
G.eval() # eval mode
# generated samples
rand_images = G(rand_z)
# 0 indicates the first set of samples in the passed in list
# and we only have one batch of ... | C:\Users\ngrec\anaconda3\envs\udl\lib\site-packages\torch\nn\functional.py:1628: UserWarning: nn.functional.tanh is deprecated. Use torch.tanh instead.
warnings.warn("nn.functional.tanh is deprecated. Use torch.tanh instead.")
| MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
DAPA Tutorial 3: Timeseries - Sentinel-2 Load environment variablesPlease make sure that the environment variable "DAPA_URL" is set in the `custom.env` file. You can check this by executing the following block. If DAPA_URL is not set, please create a text file named `custom.env` in your home directory with the follow... | from edc import setup_environment_variables
setup_environment_variables() | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Check notebook compabtibility**Please note:** If you conduct this notebook again at a later time, the base image of this Jupyter Hub service can include newer versions of the libraries installed. Thus, the notebook execution can fail. This compatibility check is only necessary when something is broken. | from edc import check_compatibility
check_compatibility("user-0.24.5", dependencies=[]) | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Load librariesPython libraries used in this tutorial will be loaded. | import os
import xarray as xr
import pandas as pd
import requests
import matplotlib
from ipyleaflet import Map, Rectangle, Marker, DrawControl, basemaps, basemap_to_tiles
%matplotlib inline | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Set DAPA endpointExecute the following code to check if the DAPA_URL is available in the environment variable and to set the `/dapa` endpoint. | service_url = None
dapa_url = None
if 'DAPA_URL' not in os.environ:
print('!! DAPA_URL does not exist as environment variable. Please make sure this is the case - see first block of this notebook! !!')
else:
service_url = os.environ['DAPA_URL']
dapa_url = '{}/{}'.format(service_url, 'oapi')
print('... | DAPA path: /oapi
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Get collections supported by this endpointThis request provides a list of collections. The path of each collection is used as starting path of this service. | collections_url = '{}/{}'.format(dapa_url, 'collections')
collections = requests.get(collections_url, headers={'Accept': 'application/json'})
print('DAPA path: {}'.format(collections.url.replace(service_url, '')))
collections.json() | DAPA path: /oapi/collections
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Get fields of collection Sentinel-2 L2AThe fields (or variables in other DAPA endpoints - these are the bands of the raster data) can be retrieved in all requests to the DAPA endpoint. In addition to the fixed set of fields, "virtual" fields can be used to conduct math operations (e.g., the calculation of indices). | collection = 'S2L2A'
fields_url = '{}/{}/{}/{}'.format(dapa_url, 'collections', collection, 'dapa/fields')
fields = requests.get(fields_url, headers={'Accept': 'application/json'})
print('DAPA path: {}'.format(fields.url.replace(service_url, '')))
fields.json() | DAPA path: /oapi/collections/S2L2A/dapa/fields
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Retrieve NDVI as 1d time-series extraced for a single point Set DAPA URL and parametersThe output of this request is a time-series requested from a point of interest (`timeseries/position` endpoint). As the input collection (S2L2A) is a multi-temporal raster and the requested geometry is a point, no aggregation is co... | # DAPA URL
url = '{}/{}/{}/{}'.format(dapa_url, 'collections', collection, 'dapa/timeseries/position')
# Parameters for this request
params = {
'point': '11.49,48.05',
'time': '2018-04-01T00:00:00Z/2018-05-01T00:00:00Z',
'fields': 'NDVI=(B08-B04)/(B08%2BB04)' # Please note: + signs need to be URL encode... | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Build request URL and conduct request | params_str = "&".join("%s=%s" % (k, v) for k,v in params.items())
r = requests.get(url, params=params_str)
print('DAPA path: {}'.format(r.url.replace(service_url, '')))
print('Status code: {}'.format(r.status_code)) | DAPA path: /oapi/collections/S2L2A/dapa/timeseries/position?point=11.49,48.05&time=2018-04-01T00:00:00Z/2018-05-01T00:00:00Z&fields=NDVI=(B08-B04)/(B08%2BB04)
Status code: 200
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Write timeseries dataset to CSV fileThe response of this request returns data as CSV including headers splitted by comma. Additional output formats (e.g., CSV with headers included) will be integrated within the testbed activtiy. You can either write the response to file or use it as string (`r.content` variable). | # write time-series data to CSV file
with open('timeseries_s2.csv', 'wb') as filew:
filew.write(r.content) | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Open timeseries dataset with pandasTime-series data can be opened, processed, and plotted easily with the `Pandas` library. You only need to specify the `datetime` column to automatically convert dates from string to a datetime object. | # read data into Pandas dataframe
ds = pd.read_csv('timeseries_s2.csv', parse_dates=['datetime'])
# set index to datetime column
ds.set_index('datetime', inplace=True)
# show dataframe
ds | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Plot NDVI data | ds.plot() | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Output CSV file | !cat timeseries_s2.csv | datetime,NDVI
2018-04-02T10:24:35Z,0.7012165
2018-04-04T10:10:21Z,0.22945666
2018-04-07T10:20:20Z,0.8333333
2018-04-09T10:13:43Z,0.63461536
2018-04-12T10:20:24Z,0.10066674
2018-04-14T10:15:36Z,0.5091714
2018-04-17T10:20:21Z,0.49720672
2018-04-19T10:14:57Z,0.68678766
2018-04-22T10:21:15Z,0.67164177
2... | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
Time-series aggregated over area | # DAPA URL
url = '{}/{}/{}/{}'.format(dapa_url, 'collections', collection, 'dapa/timeseries/area')
# Parameters for this request
params = {
#'point': '11.49,48.05',
'bbox': '11.49,48.05,11.66,48.22',
'aggregate': 'min,max,avg',
'time': '2018-04-01T00:00:00Z/2018-05-01T00:00:00Z',
'fields': 'NDVI=(B... | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_3_-_Timeseries_-_Sentinel-2.ipynb | gobaRules/notebooks |
We can see that most questions have anywhere from 15 to 150 characters in them. It seems that the test distribution is a little different from the train one, but not too much so. | dist_train = train_qs.apply(lambda x: len(x.split(' ')))
dist_test = test_qs.apply(lambda x: len(x.split(' ')))
plt.figure(figsize=(15, 10))
plt.hist(dist_train, bins=50, range=[0, 50], color=pal[2], normed=True, label='train')
plt.hist(dist_test, bins=50, range=[0, 50], color=pal[1], normed=True, alpha=0.5, label='te... | /home/manjunath/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py:6521: MatplotlibDeprecationWarning:
The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
alternative="'density'", removal="3.1")
/home/manjunath/anaconda3/lib/python3.7/site-packages/matpl... | MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
WordCloud | from wordcloud import WordCloud
cloud = WordCloud(width=1440, height=1080).generate(" ".join(train_qs.astype(str)))
plt.figure(figsize=(20, 15))
plt.imshow(cloud)
plt.axis('off') | _____no_output_____ | MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
Semantic Analysis | qmarks = np.mean(train_qs.apply(lambda x: '?' in x))
math = np.mean(train_qs.apply(lambda x: '[math]' in x))
fullstop = np.mean(train_qs.apply(lambda x: '.' in x))
capital_first = np.mean(train_qs.apply(lambda x: x[0].isupper()))
capitals = np.mean(train_qs.apply(lambda x: max([y.isupper() for y in x])))
numbers = np.m... | Questions with question marks: 99.87%
Questions with [math] tags: 0.12%
Questions with full stops: 6.31%
Questions with capitalised first letters: 99.81%
Questions with capital letters: 99.95%
Questions with numbers: 11.83%
| MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
Initial Feature AnalysisBefore we create a model, we should take a look at how powerful some features are. I will start off with the word share feature from the benchmark model. | from nltk.corpus import stopwords
stops = set(stopwords.words("english"))
def word_match_share(row):
q1words = {}
q2words = {}
for word in str(row['question1']).lower().split():
if word not in stops:
q1words[word] = 1
for word in str(row['question2']).lower().split():
if wo... | Original AUC: 0.7804327049353577
TFIDF AUC: 0.7704802292218704
| MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
Rebalancing the DataHowever, before I do this, I would like to rebalance the data that XGBoost receives, since we have 37% positive class in our training data, and only 17% in the test data. By re-balancing the data so our training set has 17% positives, we can ensure that XGBoost outputs probabilities that will bette... | # First we create our training and testing data
x_train = pd.DataFrame()
x_test = pd.DataFrame()
x_train['word_match'] = train_word_match
x_train['tfidf_word_match'] = tfidf_train_word_match
x_test['word_match'] = df_test.apply(word_match_share, axis=1, raw=True)
x_test['tfidf_word_match'] = df_test.apply(tfidf_word_ma... | _____no_output_____ | MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
XGBoost | import xgboost as xgb
# Set our parameters for xgboost
params = {}
params['objective'] = 'binary:logistic'
params['eval_metric'] = 'logloss'
params['eta'] = 0.02
params['max_depth'] = 4
d_train = xgb.DMatrix(x_train, label=y_train)
d_valid = xgb.DMatrix(x_valid, label=y_valid)
watchlist = [(d_train, 'train'), (d_val... | 3.9213494079892337
| MIT | XGBoost.ipynb | OmkarMetri/Sentence-to-Sentence-Similarity |
OmniScaleCNN> This is an unofficial PyTorch implementation by Ignacio Oguiza - oguiza@gmail.com based on:* Rußwurm, M., & Körner, M. (2019). Self-attention for raw optical satellite time series classification. arXiv preprint arXiv:1910.10536.* Official implementation: https://github.com/dl4sits/BreizhCrops/blob/master... | #export
from tsai.imports import *
from tsai.models.layers import *
from tsai.models.utils import *
#export
#This is an unofficial PyTorch implementation by Ignacio Oguiza - oguiza@gmail.com based on:
# Rußwurm, M., & Körner, M. (2019). Self-attention for raw optical satellite time series classification. arXiv preprint... | _____no_output_____ | Apache-2.0 | nbs/109_models.OmniScaleCNN.ipynb | ansari1375/tsai |
Natural Language Processing - Unsupervised Topic Modeling with Reddit Posts This project dives into multiple techniques used for NLP and subtopics such as dimensionality reduction, topic modeling, and clustering.1. [Google BigQuery](Google-BigQuery)1. [Exploratory Data Analysis (EDA) & Preprocessing](Exploratory-Data-... | # Easter Egg to start your imports
#import this
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import logging
import pickle
import sys
import os
from google.cloud import bigquery
import warnings
def warn(*args, **kwargs):
pass
warnings.warn = warn
# Logging is the ve... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Google BigQuery | %%time
path = "data/posts.pkl"
key = 'fakeKey38i7-4259.json'
if not os.path.isdir('data/'):
os.makedirs('data/')
# Set GOOGLE_APPLICATION_CREDENTIALS before querying
def bigQuery(QUERY, key=key):
"""
Instantiates a client using a key,
Requests a SQL query from the Big Query API,
Returns the que... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 146996 entries, 0 to 146995
Data columns (total 13 columns):
created_utc 146996 non-null int64
subreddit 146996 non-null object
author 146996 non-null object
domain 146996 non-null object
url 146996 non-null object
num_comments ... | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Exploratory Data Analysis & Preprocessing | # Exploring data by length of .title or .selftext
df[[ True if 500 < len(x) < 800 else False for x in df.selftext ]].sample(1, replace=False)
%%time
run = False
path = '/home/User/data/gif'
# Run through various selftext lengths and save the plots of the distribution of the metric
# Gif visual after piecing all the fr... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Tokenization is one of the most important steps in NLP, I will explain some of my parameter choices in the README. CountVectorizer was my preferred choice. I used these definitions to help me in the iterative process of building an unsupervised model. The goal of using tf-idf instead of the raw frequencies of occurren... | %%time
# Count & tf-idf vectorizer fits the tokenizer and transforms data into new matrix
cv_vecs = cv.fit_transform(df.text).transpose()
tf_vecs = tfidf.fit_transform(df.text).transpose()
pickle.dump(cv_vecs, open('data/cv_vecs.pkl', 'wb'))
# Checking the shape and size of the count vectorizer transformed matrix
# 47... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Singular Value Decomposition (SVD) | #from sklearn.utils.extmath import randomized_svd
# Randomized SVD for extracting the full decomposition
#U, Sigma, VT = randomized_svd(tf_vecs, n_components=8, random_state=42)
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer
def Trunc_SVD(vectorized, n_components=300, iter... | Explained Variance Ratio (EVR):
[0.00400 0.00357 0.00222 0.00220 0.00184 0.00166 0.00158 0.00145 0.00128
0.00123 0.00122 0.00113 0.00111 0.00106 0.00103 0.00098 0.00097 0.00095
0.00092 0.00088]
Difference in EVR (start 3):
[-0.00002 -0.00036 -0.00017 -0.00008 -0.00013 -0.00017 -0.00005 -0.00001
-0.00009 -0.00003 -... | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
The count vectorizer seems like it will be more fool proof, so I will use cv for my study. 8 might be a good cutoff value for the number of components kept in dimensionality reduction, I will try to confirm this later with KMeans clustering. The intuition behind this is that the slope after the 8th element is signific... | %%time
from gensim import corpora, matutils, models
# Convert sparse matrix of term-doc counts to a gensim corpus
cv_corpus = matutils.Sparse2Corpus(cv_vecs)
pickle.dump(cv_corpus, open('data/cv_corpus.pkl', 'wb'))
# Maps index to term
id2word = dict((v, k) for k, v in cv.vocabulary_.items())
# This is for Python 3,... | -1.4106649569930907
-0.031444038368904303
-1.2723604749491777
0.15042521472269477
0.690384834127101
| MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Similarity Scoring | from gensim import similarities
# Create an index transformer that calculates similarity based on our space
index = similarities.MatrixSimilarity(doc_vecs, num_features=300)
# Return the sorted list of cosine similarities to the docu document
docu = 5 # Change docu as needed
sims = sorted(enumerate(index[doc_vecs[doc... |
Score: 0.99999994
Document Text:
I just recharged the A/C on my 2008 328xi Just wanted to share my success story.
This was an extremely easy project, after about 10 minutes of research.
The most difficult part was knowing which knob was the low-pressure service knob. After I convinced myself I had it right, the ent... | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
The metrics look artifically high, and do not match well for each document. The similarity method could be used to optimize keyword search if we were trying to expand the reach of a certain demographic using these rankings. The next step would be to improve on this method with word2vec or a better LSI model. KMeans C... | lsi_red = matutils.corpus2dense(lsi_corpus, num_terms=300).transpose()
print('Reduced LS space shape:', lsi_red.shape)
print('Reduced LS space size in bytes:', sys.getsizeof(lsi_red))
# Taking a subset for Kmeans due to memory dropout
lsi_red_sub = lsi_red.copy()
np.random.shuffle(lsi_red_sub)
lsi_red_sub = lsi_red_su... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
This suggests that there arent meaningful clusters in the normalized LS300 space. To test if 300 dimensions is too large, I will try clustering again with a reduced input. | # Fix IndexError: index 10
lsi_red5 = matutils.corpus2dense(lsi_corpus, num_terms=10).transpose()
print('Reduced LSI space shape:', lsi_red5.shape)
print('Reduced LS space subset size in bytes:', sys.getsizeof(lsi_red5))
# Taking a subset for Kmeans due to memory dropout
lsi_red_sub5 = lsi_red5.copy()
np.random.shuffl... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Due to project deadlines, I was not able to complete this method but I wanted to preserve the effort and document the process for later use. I will move on to LDA. | # Cluster with the best results
#kmeans = KMeans(n_clusters=20, n_jobs=-2)
#lsi_clusters = kmeans.fit_predict(lsi_red)
# Take a look at the
print(lsi_clusters[0:15])
df.text[0:2]
from sklearn.metrics import silhouette_samples, silhouette_score
# Validating cluster performance
# Select range around best result, plot ... | _____no_output_____ | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Latent Dirichlet Allocation (LDA) | %%time
run = False
passes = 85
if run==True:
lda = models.LdaMulticore(corpus=cv_corpus, num_topics=15, id2word=id2word, passes=passes,
workers=13, random_state=42, eval_every=None, chunksize=6000)
# Save model after your last run, or continue to update LDA
#pickle.dump(lda, open('da... | 2018-03-11 07:47:06,762 : INFO : topic #1 (0.067): 0.005*"water" + 0.005*"food" + 0.004*"use" + 0.003*"make" + 0.003*"much" + 0.003*"used" + 0.003*"well" + 0.003*"skin" + 0.003*"first" + 0.003*"good"
| MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
pyLDAvis | # For quickstart, we can just jump straight to results
import pickle
from gensim import models
def loadingPickles():
id2word = pickle.load(open('data/id2word.pkl','rb'))
cv_vecs = pickle.load(open('data/cv_vecs.pkl','rb'))
cv_corpus = pickle.load(open('data/cv_corpus.pkl','rb'))
lda = models.LdaModel.l... | /usr/local/lib/python3.5/dist-packages/pyLDAvis/_prepare.py:387: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
topic_term_dists = topic_te... | MIT | NLP-Reddit.ipynb | daviscvance/NLP-Reddit |
Forecasting in StatsmodelsThis notebook describes forecasting using time series models in Statsmodels.**Note**: this notebook applies only to the state space model classes, which are:- `sm.tsa.SARIMAX`- `sm.tsa.UnobservedComponents`- `sm.tsa.VARMAX`- `sm.tsa.DynamicFactor` | %matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
macrodata = sm.datasets.macrodata.load_pandas().data
macrodata.index = pd.period_range('1959Q1', '2009Q3', freq='Q') | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Basic exampleA simple example is to use an AR(1) model to forecast inflation. Before forecasting, let's take a look at the series: | endog = macrodata['infl']
endog.plot(figsize=(15, 5)) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Constructing and estimating the model The next step is to formulate the econometric model that we want to use for forecasting. In this case, we will use an AR(1) model via the `SARIMAX` class in Statsmodels.After constructing the model, we need to estimate its parameters. This is done using the `fit` method. The `summ... | # Construct the model
mod = sm.tsa.SARIMAX(endog, order=(1, 0, 0), trend='c')
# Estimate the parameters
res = mod.fit()
print(res.summary()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Forecasting Out-of-sample forecasts are produced using the `forecast` or `get_forecast` methods from the results object.The `forecast` method gives only point forecasts. | # The default is to get a one-step-ahead forecast:
print(res.forecast()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
The `get_forecast` method is more general, and also allows constructing confidence intervals. | # Here we construct a more complete results object.
fcast_res1 = res.get_forecast()
# Most results are collected in the `summary_frame` attribute.
# Here we specify that we want a confidence level of 90%
print(fcast_res1.summary_frame(alpha=0.10)) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
The default confidence level is 95%, but this can be controlled by setting the `alpha` parameter, where the confidence level is defined as $(1 - \alpha) \times 100\%$. In the example above, we specified a confidence level of 90%, using `alpha=0.10`. Specifying the number of forecastsBoth of the functions `forecast` an... | print(res.forecast(steps=2))
fcast_res2 = res.get_forecast(steps=2)
# Note: since we did not specify the alpha parameter, the
# confidence level is at the default, 95%
print(fcast_res2.summary_frame()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
However, **if your data included a Pandas index with a defined frequency** (see the section at the end on Indexes for more information), then you can alternatively specify the date through which you want forecasts to be produced: | print(res.forecast('2010Q2'))
fcast_res3 = res.get_forecast('2010Q2')
print(fcast_res3.summary_frame()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Plotting the data, forecasts, and confidence intervalsOften it is useful to plot the data, the forecasts, and the confidence intervals. There are many ways to do this, but here's one example | fig, ax = plt.subplots(figsize=(15, 5))
# Plot the data (here we are subsetting it to get a better look at the forecasts)
endog.loc['1999':].plot(ax=ax)
# Construct the forecasts
fcast = res.get_forecast('2011Q4').summary_frame()
fcast['mean'].plot(ax=ax, style='k--')
ax.fill_between(fcast.index, fcast['mean_ci_lower... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Note on what to expect from forecastsThe forecast above may not look very impressive, as it is almost a straight line. This is because this is a very simple, univariate forecasting model. Nonetheless, keep in mind that these simple forecasting models can be extremely competitive. Prediction vs ForecastingThe results ... | # Step 1: fit model parameters w/ training sample
training_obs = int(len(endog) * 0.8)
training_endog = endog[:training_obs]
training_mod = sm.tsa.SARIMAX(
training_endog, order=(1, 0, 0), trend='c')
training_res = training_mod.fit()
# Print the estimated parameters
print(training_res.params)
# Step 2: produce on... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
To add on another observation, we can use the `append` or `extend` results methods. Either method can produce the same forecasts, but they differ in the other results that are available:- `append` is the more complete method. It always stores results for all training observations, and it optionally allows refitting the... | # Step 1: append a new observation to the sample and refit the parameters
append_res = training_res.append(endog[training_obs:training_obs + 1], refit=True)
# Print the re-estimated parameters
print(append_res.params) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Notice that these estimated parameters are slightly different than those we originally estimated. With the new results object, `append_res`, we can compute forecasts starting from one observation further than the previous call: | # Step 2: produce one-step-ahead forecasts
fcast = append_res.forecast()
# Step 3: compute root mean square forecasting error
true = endog.reindex(fcast.index)
error = true - fcast
# Print out the results
print(pd.concat([true.rename('true'),
fcast.rename('forecast'),
error.rename('e... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Putting it altogether, we can perform the recursive forecast evaluation exercise as follows: | # Setup forecasts
nforecasts = 3
forecasts = {}
# Get the number of initial training observations
nobs = len(endog)
n_init_training = int(nobs * 0.8)
# Create model for initial training sample, fit parameters
init_training_endog = endog.iloc[:n_init_training]
mod = sm.tsa.SARIMAX(training_endog, order=(1, 0, 0), tren... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
We now have a set of three forecasts made at each point in time from 1999Q2 through 2009Q3. We can construct the forecast errors by subtracting each forecast from the actual value of `endog` at that point. | # Construct the forecast errors
forecast_errors = forecasts.apply(lambda column: endog - column).reindex(forecasts.index)
print(forecast_errors.iloc[:5, :5]) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
To evaluate our forecasts, we often want to look at a summary value like the root mean square error. Here we can compute that for each horizon by first flattening the forecast errors so that they are indexed by horizon and then computing the root mean square error fore each horizon. | # Reindex the forecasts by horizon rather than by date
def flatten(column):
return column.dropna().reset_index(drop=True)
flattened = forecast_errors.apply(flatten)
flattened.index = (flattened.index + 1).rename('horizon')
print(flattened.iloc[:3, :5])
# Compute the root mean square error
rmse = (flattened**2).me... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Using `extend`We can check that we get similar forecasts if we instead use the `extend` method, but that they are not exactly the same as when we use `append` with the `refit=True` argument. This is because `extend` does not re-estimate the parameters given the new observation. | # Setup forecasts
nforecasts = 3
forecasts = {}
# Get the number of initial training observations
nobs = len(endog)
n_init_training = int(nobs * 0.8)
# Create model for initial training sample, fit parameters
init_training_endog = endog.iloc[:n_init_training]
mod = sm.tsa.SARIMAX(training_endog, order=(1, 0, 0), tren... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
By not re-estimating the parameters, our forecasts are slightly worse (the root mean square error is higher at each horizon). However, the process is faster, even with only 200 datapoints. Using the `%%timeit` cell magic on the cells above, we found a runtime of 570ms using `extend` versus 1.7s using `append` with `ref... | print(endog.index) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
In most cases, if your data has an associated data/time index with a defined frequency (like quarterly, monthly, etc.), then it is best to make sure your data is a Pandas series with the appropriate index. Here are three examples of this: | # Annual frequency, using a PeriodIndex
index = pd.period_range(start='2000', periods=4, freq='A')
endog1 = pd.Series([1, 2, 3, 4], index=index)
print(endog1.index)
# Quarterly frequency, using a DatetimeIndex
index = pd.date_range(start='2000', periods=4, freq='QS')
endog2 = pd.Series([1, 2, 3, 4], index=index)
print(... | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
In fact, if your data has an associated date/time index, it is best to use that even if does not have a defined frequency. An example of that kind of index is as follows - notice that it has `freq=None`: | index = pd.DatetimeIndex([
'2000-01-01 10:08am', '2000-01-01 11:32am',
'2000-01-01 5:32pm', '2000-01-02 6:15am'])
endog4 = pd.Series([0.2, 0.5, -0.1, 0.1], index=index)
print(endog4.index) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
You can still pass this data to Statsmodels' model classes, but you will get the following warning, that no frequency data was found: | mod = sm.tsa.SARIMAX(endog4)
res = mod.fit() | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
What this means is that you cannot specify forecasting steps by dates, and the output of the `forecast` and `get_forecast` methods will not have associated dates. The reason is that without a given frequency, there is no way to determine what date each forecast should be assigned to. In the example above, there is no p... | res.forecast(1) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
The index associated with the new forecast is `4`, because if the given data had an integer index, that would be the next value. A warning is given letting the user know that the index is not a date/time index.If we try to specify the steps of the forecast using a date, we will get the following exception: KeyError:... | # Here we'll catch the exception to prevent printing too much of
# the exception trace output in this notebook
try:
res.forecast('2000-01-03')
except KeyError as e:
print(e) | _____no_output_____ | BSD-3-Clause | examples/notebooks/statespace_forecasting.ipynb | diego-mazon/statsmodels |
Naas - Get help **Tags:** naas help Input Import needed library | import naas | _____no_output_____ | BSD-3-Clause | Naas/Naas_Get_help.ipynb | Charles-de-Montigny/awesome-notebooks |
Output Open help chatbox | naas.open_help() | _____no_output_____ | BSD-3-Clause | Naas/Naas_Get_help.ipynb | Charles-de-Montigny/awesome-notebooks |
Close help chatbox | naas.close_help() | _____no_output_____ | BSD-3-Clause | Naas/Naas_Get_help.ipynb | Charles-de-Montigny/awesome-notebooks |
Les commentaires
Lorsque vous écrivez un programme, vous serez le plus souvent appelé à commenter vos lignes de code afin de vous les expliquer à vous ou aux autres programmeurs qui vous liront; c'est une bonne pratique.
Les commentaires entre codes facilitent aux humains la compréhension du code et par conséquent, ils... | '''
Fonction pour dire bonjour à l'utilisateur :
cette fonction va afficher un message sympa à l'écran
'''
def direBonjour():
print('Bonjour cher utilisateur')
#ici j'appelle ma fonction
direBonjour() | Bonjour cher utilisateur
| MIT | docs/chap02-02-commentaires.ipynb | bellash13/SmartAcademyPython |
Visualise> Visualise the datacube interactively. | #hide
from nbdev.showdoc import * | _____no_output_____ | CC-BY-3.0 | 04_visualise.ipynb | YiweiMao/openhsi |
Lendo/Tratando dados | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.read_csv('emotions.csv')
sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis')
df.columns[2548] | _____no_output_____ | MIT | ML/Teste2 - HMM/.ipynb_checkpoints/Teste2- v1-checkpoint.ipynb | Vinschers/egg-waves |
Treinando modelo | from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(df.drop('label',axis=1),
df['label'], test_size=0.30)
from sklearn.hmm import MultinomialHMM
dtree = RandomForestClassifier(n_estimators = 200)
dtree.fit(x_train... | _____no_output_____ | MIT | ML/Teste2 - HMM/.ipynb_checkpoints/Teste2- v1-checkpoint.ipynb | Vinschers/egg-waves |
Teste para Erro | x_train, x_test, y_train, y_test = train_test_split(df.drop('label',axis=1),
df['label'], test_size=0.30)
y_train_forjado = []
for i in range(0, 1492):
y_train_forjado.append('POSITIVE')
type(y_train)
dtree = DecisionTreeClassifier()
dtree.fit(x_train, pd.Serie... | precision recall f1-score support
NEGATIVE 0.00 0.00 0.00 228
NEUTRAL 0.00 0.00 0.00 221
POSITIVE 0.30 1.00 0.46 191
accuracy 0.30 640
macro avg 0.10 0.33 0.15 ... | MIT | ML/Teste2 - HMM/.ipynb_checkpoints/Teste2- v1-checkpoint.ipynb | Vinschers/egg-waves |
Notebook to visualize location data | import csv
# count the number of Starbucks in DC
with open('starbucks.csv') as file:
csvinput = csv.reader(file)
acc = 0
for record in csvinput:
if 'DC' in record[3]:
acc += 1
print( acc )
def parse_locations(csv_iterator,state=''):
""" strip out long/lat and convert to a l... | _____no_output_____ | MIT | locations.ipynb | hystx1/csc280 |
But where's AU? | # draw both the starbucks location and DC boundary together
plt.figure(figsize=(12, 9))
ax = plt.axes()
ax.set_aspect('equal', 'datalim')
plt.scatter(*zip(*starbucks_dc_locations))
plt.scatter(*zip(*burger_dc_locations), color='green')
plt.plot(*zip(*dc_boundary))
# add a red dot right over Anderson
plt.scatter([-7... | _____no_output_____ | MIT | locations.ipynb | hystx1/csc280 |
Dense DAISY feature descriptionhttps://scikit-image.org/docs/dev/auto_examples/features_detection/plot_daisy.htmlfrom | from skimage.feature import daisy
from skimage import data
import matplotlib.pyplot as plt
%%time
img = data.camera()
descs = daisy(img, step=5, radius=8, visualize=True)
descs.shape | _____no_output_____ | MIT | notebooks/Hello-DAISY.ipynb | k-sunako/learning-DAISY-feat-desc |
RegularizationWelcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it... | # import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.da... | _____no_output_____ | MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head. **Figure 1** : **Football field** The goal keeper kicks the ... | train_X, train_Y, test_X, test_Y = load_2D_dataset() | _____no_output_____ | MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.- If the dot is blue, it means the French player managed to hit the ball with his/her head- If the dot is red, it me... | def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 ... | _____no_output_____ | MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
Let's train the model without any regularization, and observe the accuracy on the train/test sets. | parameters = model(train_X, train_Y)
print ("On the training 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.6557412523481002
Cost after iteration 10000: 0.16329987525724216
Cost after iteration 20000: 0.13851642423255986
| MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model. | plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
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/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting. 2 - L2 RegularizationThe standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from:$$J = -... | # GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examp... | cost = 1.78648594516
| MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Expected Output**: **cost** 1.78648594516 Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost. **Exercise**: Implement the changes needed in backward propagation to take i... | # GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of example... | dW1 = [[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
dW2 = [[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]
dW3 = [[-1.77691347 -0.11832879 -0.09397446]]
| MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Expected Output**: **dW1** [[-0.25604646 0.12298827 -0.28297129] [-0.17706303 0.34536094 -0.4410571 ]] **dW2** [[ 0.79276486 0.85133918] [-0.0957219 -0.01720463] [-0.13100772 -0.03750433]] **dW3** [[-1.77691347 -0.11832... | parameters = model(train_X, train_Y, lambd = 0.7)
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.6974484493131264
Cost after iteration 10000: 0.2684918873282239
Cost after iteration 20000: 0.2680916337127301
| MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
Congrats, the test set accuracy increased to 93%. You have saved the French football team!You are not overfitting the training data anymore. Let's plot the decision boundary. | plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
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/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Observations**:- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.**What is L2-regularization actually doing?**:L2-regularization r... | # GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of example... | A3 = [[ 0.49683389 0.49683389 0.49683389 0.36974721 0.49683389]]
| MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Expected Output**: **A3** [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]] 3.2 - Backward propagation with dropout**Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second h... | # GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector... | dA1 = [[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
dA2 = [[ 0.58180856 0. -0.00299679 0. -0.27715731]
[ 0. 0.53159854 -0. 0.53159854 -0.34089673]
[ 0. 0. -0.00292733 0. -0. ... | MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
**Expected Output**: **dA1** [[ 0.36544439 0. -0.00188233 0. -0.17408748] [ 0.65515713 0. -0.00337459 0. -0. ]] **dA2** [[ 0.58180856 0. -0.00299679 0. -0.27715731] [ 0. 0.53159854 -0.... | parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
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) | _____no_output_____ | MIT | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you! Run the code below to plot the decision boundary. | plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
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/Regularization/Regularization+-+v2.ipynb | fera0013/deep-learning-specialization-coursera |
Calculating intensity in an inclined direction $\cos\theta \neq 1$ For this first part we are going to use our good old FALC model and calculate intensity in direction other than $\mu = 1$. This is also an essential part of scattering problems! We will assume that we are dealing with continuum everywhere! | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({
"text.usetex": False,
"font.size" : 16,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})
# Let's load the data:
atmos = np.loadtxt("falc_71.dat",unpack=True,skiprows=1)
atmos.shape
# 0th pa... | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
We want to use a very simple formal solution: $$I = I_{inc} e^{-\Delta \tau} + S(1-e^{-\Delta \tau}) $$ | # Let's define a function that is doing that:
def synthesis_whole(S,tau):
ND = len(S)
intensity = np.zeros(ND)
# At the bottom, intensity is equal to the source function (similar to Blackbody)
intensity[ND-1] = S[ND-1]
for d in range(ND-2,-1,-1):
# optical thickness of the la... | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Discuss this 3-4 mins. Write the conclusions here:Intensity is not the same as the source function. It is "nonlocal" (ok Ivan, we get it, you said million times!) Now how about using a grid of $mu$ angles? We are solving $$\mu \frac{dI}{d\tau} = I-S $$ $$\frac{dI}{d\tau / \mu} = I-S $$ $\mu$ goes from 0 to 1 | NM = 10
ND = len(S)
# create mu grid
mu = np.linspace(0.1,1.0,NM)
intensity_grid = np.zeros([NM,ND])
# Calculate the intensity in each direction:
for m in range(0,10):
intensity_grid[m] = synthesis_whole(S,tau/mu[m])
plt.figure(figsize=[9,5])
plt.plot(mu,intensity_grid[:,0])
plt.ylabel("$I^+(\mu)$")
plt.xlabel(... | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Limb darkening! Limb darkening explanation: Now the scattering problem! Solve, iteratively: $$S = \epsilon B + (1-\epsilon) J $$ $$ J = \frac{1}{4\pi} \int_0^{\pi} \int_0^{2\pi} I(\theta,\phi) \sin \theta d\theta d\phi = \frac{1}{2} \int_{-1}^{1}... | # simplified trapezoidal rule:
# Starting value:
J = 0.
for m in range(0,NM-1):
J += (intensity_grid[m,0] + intensity_grid[m+1,0]) * (mu[m+1] - mu[m])/2.0
J *= 0.5
print ("ratio of the mean intensity at the surface to the Planck function at the surface is: ", J/B[0]) | ratio of the mean intensity at the surface to the Planck function at the surface is: 0.11910542541966643
| MIT | Simple scattering .ipynb | ivanzmilic/collage |
Now the next step would be, to say: $$S = \epsilon B + \epsilon J $$There are, however, few hurdles before that: - We don't know $\epsilon$. Let's assume there is a lot of scattering and set $\epsilon=10^{-2}$- We don't know J everywhere, we only calculate at the top. This one is harder to fix. To really calculate J ... | # Old RTE solver looks like this. Renamed it to out so that we know it is the outgoing intensity
def synthesis_out(S,tau):
ND = len(S)
intensity = np.zeros(ND)
# At the bottom, intensity is equal to the source function (similar to Blackbody)
intensity[ND-1] = S[ND-1]
for d in range(N... | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Take a moment here and try to think about these two things: - The intensity at the bottom is much more close to each other and much less strongly depends on $\mu$. Would you call that situation "isotropic"?- Why is this so? | # Now we can calculate mean intensity similarly to above. We don't even have to use super strict
# trapezoidal integration. Just add all the intensities and divide by 20
J = np.sum(int_in+int_out,axis=0)/20.
# Then define the epsilon
epsilon = 1E-2
# And then we can update the source function:
S = epsilon * B + (1-... | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Now: This is new value of the source function! We should now recalculate the new intensity. But wait, this new intensity now results in a new Source function. Which then results in the new intensity....This leads to an iterative process, known as "Lambda" iteration. We repeat the process until (a very slow) convergence... | # I will define an additional function to make things clearer:
def update_S(int_in, int_out, epsilon, B):
J = np.sum(int_in+int_out,axis=0)/20.
S = epsilon * B + (1-epsilon) * J
return S
# And then we devise an iterative scheme:
max_iter = 100
# Start from the source function equal to the Planck function... | Relative change in this iteration is: 1.3314924320494517
Relative change in this iteration is: 0.04805746551383416
Relative change in this iteration is: 0.022455016014927415
Relative change in this iteration is: 0.019691776769293193
Relative change in this iteration is: 0.01776157724309405
Relative change in this ... | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Spend some time figuring this out. This is a common technique for solving various kinds of coupled equations in astrophysics! To finish the story let's visualize the final solution of this, and then do one more example - constant temperature! | plt.figure(figsize=[9,5])
plt.plot(logtau,B,label="Planck Function")
plt.plot(logtau,S,label="Source Function")
plt.xlabel("$\\log \\tau$")
plt.title("Scattering Source function")
plt.legend() | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
It drops very very very low, even in great depths! This is exactly not the greatest example as in the great depths the epsilon will never be so small. Epsilon is generally depth dependent. Example - Scattering in an isothermal atmosphere | ## We will do all the same as before except we will now use a different tau grid, to make atmosphere
# much deeper. And we will use B = const, to reproduce some plots from the literature:
logtau = np.linspace(-4,4,81)
tau = 10.**logtau
ND = len(logtau)
B = np.zeros(ND)
B[:] = 1.0 # Units do not matter, we can say ever... | Relative change in this iteration is: 0.495
Relative change in this iteration is: 0.24554435193688087
Relative change in this iteration is: 0.16165180317576575
Relative change in this iteration is: 0.11907785184516301
Relative change in this iteration is: 0.0934605504492721
Relative change in this iteration is: 0... | MIT | Simple scattering .ipynb | ivanzmilic/collage |
We have reached some sort of convergence. (Relative change of roughly 1E-3).Let's have a look at our source function: | plt.figure(figsize=[9,5])
plt.plot(logtau,B,label="Planck Function")
plt.plot(logtau,S,label="Source Function")
plt.xlabel("$\\log \\tau$")
plt.title("Scattering (NLTE) Source function")
plt.legend() | _____no_output_____ | MIT | Simple scattering .ipynb | ivanzmilic/collage |
Working with code cellsIn this notebook you'll get some experience working with code cells.First, run the cell below. As I mentioned before, you can run the cell by selecting it the click the "run cell" button above. However, it's easier to run it by pressing **Shift + Enter** so you don't have to take your hands away... | # Select the cell, then press Shift + Enter
3**2 | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Shift + Enter runs the cell then selects the next cell or creates a new one if necessary. You can run a cell without changing the selected cell by pressing **Control + Enter**.The output shows up below the cell. It's printing out the result just like in a normal Python shell. Only the very last result in a cell will be... | 3**2
4**2
print(3**2)
4**2 | 9
| MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Now try assigning a value to a variable. | import string
mindset = 'growth'
codes = [string.ascii_letters.index(char) for char in mindset] | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
There is no output, `'growth'` has been assigned to the variable `mindset`. All variables, functions, and classes created in a cell are available in every other cell in the notebook.What do you think the output will be when you run the next cell? Feel free to play around with this a bit to get used to how it works. | print(mindset[:4])
print(codes) | grow
[6, 17, 14, 22, 19, 7]
| MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Code completionWhen you're writing code, you'll often be using a variable or function often and can save time by using code completion. That is, you only need to type part of the name, then press **tab**.> **Exercise:** Place the cursor at the end of `mind` in the next cell and press **tab** | mindset | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Here, completing `mind` writes out the full variable name `mindset`. If there are multiple names that start the same, you'll get a menu, see below. | # Run this cell
mindful = True
# Complete the name here again, choose one from the menu
mindful
| _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.