markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Visualize weights for the Conv2D layer. The structural sparsity is applied in the last channel, similar to the Dense layer. Only the second Conv2D layer is structurally pruned as pointed out above. | # Get weights of the convolutional layer that has been pruned with 2 by 4 sparsity.
tensor_name = 'structural_pruning/Conv2D'
detail = [x for x in details if tensor_name in x["name"]]
tensor_data = interpreter.tensor(detail[1]["index"])()
print(f"Shape of the weight tensor is {tensor_data.shape}") | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Similar to the weights of Dense layer, the last dimension of the kernel has a (2, 4) structure. | weights_to_display = tf.reshape(tensor_data, [tf.reduce_prod(tensor_data.shape[:-1]), -1])
weights_to_display = weights_to_display[0:width, 0:height]
val_ones = np.ones([height, width])
val_zeros = np.zeros([height, width])
subset_values_to_display = np.where(abs(weights_to_display) > 1e-9, val_ones, val_zeros)
plot_... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Let's see how those randomly pruned weights look. We extract them and display a subset of the weight tensor. | # Get weights of the convolutional layer that has been pruned with random pruning.
tensor_name = 'pruning_sparsity_0_5/Conv2D'
detail = [x for x in details if tensor_name in x["name"]]
tensor_data = interpreter.tensor(detail[0]["index"])()
print(f"Shape of the weight tensor is {tensor_data.shape}")
weights_to_display ... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
The TensorFlow Model Optimization Toolkit includes a python script that can be used to check whether which layers in the model from the given tflite file have the structurally pruned weights: check_sparsity_m_by_n.py. The following command demonstrates how to use this tool to check for 2 by 4 sparsity in a specific mod... | ! python3 ./tensorflow_model_optimization/python/core/sparsity/keras/tools/check_sparsity_m_by_n.py --model_tflite=pruned_model.tflite --m_by_n=2,4
| site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Connect to server | lgn = Lightning(ipython=True, host='http://public.lightning-viz.org') | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> One random line with default styles
To experience Lightning's custom zoom behaviors, try zooming and panning with the alt or command keys held down.
<br>
Alt will only zoom/pan in x (especially useful for time series), and command for y. | y = gaussian_filter(random.rand(100), 3)
lgn.line(y) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> Setting line width and color
For a single line you can pass one size and color. | y = gaussian_filter(random.rand(100), 3)
lgn.line(y, thickness=10, color=[255,100,100]) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> Multiple lines
Colors for multiple lines will automatically be assigned. Try hovering over a line to highlight it! | y = gaussian_filter(random.rand(5,100), [0, 3])
y = (y.T + arange(0,5)*0.2).T
lgn.line(y, thickness=6) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
You can also set colors and thicknesses yourself, providing one per line. Here we do so using a palette from seaborn. | y = gaussian_filter(random.rand(5,100), [0, 3])
y = (y.T + arange(0,5)*0.2).T
c = map(lambda x: list(asarray(x)*255), color_palette('Blues', 5))
s = [8, 10, 12, 14, 16]
lgn.line(y, thickness=s, color=c) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> Staggered lines and indices
It's possible to show multiple lines of unequal length.
<br>
Here we also demonstrate passing an index to set the xaxis (we assume the index corresponds to the longest of the lines). | y1 = gaussian_filter(random.rand(50), 5).tolist()
y2 = gaussian_filter(random.rand(75), 5).tolist()
y3 = gaussian_filter(random.rand(100), 5).tolist()
x = range(50,150)
lgn.line([y1,y2,y3], thickness=6, index=x) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> Clustered series with group labels
Instead of specifying colors directly as rgb, you can specify group assignments.
<br>
Here we use scikitlearn to generate clusters and then color according to cluster label. | d, g = datasets.make_blobs(n_features=5, n_samples=20, centers=5, cluster_std=1.0, random_state=100)
lgn.line(d, group=g) | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
<hr> Axis labels
You can also label the axes. | y = gaussian_filter(random.rand(100), 3)
lgn.line(y, thickness=10, xaxis='variable #1', yaxis='variable #2') | plots/line.ipynb | RaoUmer/lightning-example-notebooks | mit |
Estatística e vetores
Podemos utilizar vetores para registrar uma série de medições de um mesmo fenômeno. Um sinal digitalizado, por exemplo, pode ser considerado um vetor. Assim, é possível tomar um certo conjunto de amostras de dois sinais e calcular sua distância Euclidiana, por exemplo. Na notação que aplicamos par... | # Demonstrando propriedades de vetores
# Ideia: coloque mais dimensoes nos vetores e veja o que acontece!
x = np.array([-40, -30, 30, 40])
y = np.array([3, 4, -3, -4])
z = np.array([0, 1, -6, -7])
print np.mean(x), np.mean(y), np.mean(z) # Medias
print np.var(x), np.var(y), np.var(z) # Variancias | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Normalizando vetores
Uma operação matemática interessante que podemos fazer é a de normalizar vetores. Esta operação resulta em um vetor com média zero e variância unitária. O vetor $\boldsymbol x_{\mbox{normalizado}}$ pode ser calculado por:
$$\boldsymbol x_{\mbox{normalizado}} = \frac{\boldsymbol x-\mu_x}{\sigma_x}.$... | x = np.array([4, 3, 2, 4, 3.2, 1, 2, 90, 1, 2, 3, 4])
x_norm = (x - np.mean(x))/np.sqrt(np.var(x))
print np.mean(x), np.mean(x_norm)
print np.var(x), np.var(x_norm) | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Análise estatística de descritores de áudio
Nesta análise, vamos verificar como as estatísticas de descritores de áudio podem ser utilizadas para identificar, de forma objetiva, o conteúdo de descritores.
No código que segue, calcularemos o flatness espectral ao longo de quadros de curta duração de três trechos de áudi... | import mir3.modules.tool.wav2spectrogram as spectrogram
import mir3.modules.features.flatness as flatness
fnames = ['audio/tabla.wav', 'audio/bbking.wav', 'audio/chorus.wav']
flat_samples = []
for fname in fnames:
wav2spec = spectrogram.Wav2Spectrogram() # Objeto que converte arquivos wav para espectrogramas
s... | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Podemos, neste momento, detectar alguns comportamentos interessantes:
* O flatness do coral permanece o tempo todo abaixo de 0.1
* Embora o flatness da guitarra seja, em geral, baixo, também pode subir para valores mais altos
* O flatness da tabla tem uma dispersão muito grande entre 0 e 0.45.
Veja que essas observaçõe... | m = []
s =[]
for a in xrange(3):
m.append(np.mean(flat_samples[a]))
s.append(np.var(flat_samples[a]))
print fnames[a], np.mean(flat_samples[a]), np.var(flat_samples[a]) | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
É importante perceber que este procedimento permite relacionar arquivos de áudio a um vetor, de tantas dimensões quanto se queira (poderíamos expandir este procedimento para incluir outros descritores, por exemplo).
Esses vetores podem ser mostrados numa figura: | color=['red', 'blue', 'green']
label=['Tabla', 'Guitarra', 'Coral']
plt.figure();
for a in xrange(len(m)):
plt.scatter(m[a], s[a], color=color[a], label=label[a])
plt.xlabel('Media de flatness')
plt.ylabel('Variancia de flatness')
plt.legend(label, loc=4);
plt.show() | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Generalização
Até o momento, mostramos como relacionar arquivos de áudio a vetores, mas não há nenhuma prova de que esses vetores são representativos quanto ao conteúdo acústico que utilizamos como base. Vamos começar esse processo de forma anedotal, utilizando o arquivo de áudio que foi usado como exercício na unidade... | wav2spec = spectrogram.Wav2Spectrogram() # Objeto que converte arquivos wav para espectrogramas
spec = wav2spec.convert(open('audio/testing.wav', 'rb'), window_length=1024, window_step=512, spectrum_type='magnitude')
fness = flatness.Flatness()
f = fness.calc_track(spec)
m.append(np.mean(f.data))
s.append(np.var(f.data... | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Podemos visualizar que o ponto de teste parece mais próximo do vetor da Tabla que dos demais. Podemos calcular essa distância: | for i in xrange(3):
print label[i], np.linalg.norm( np.array([s[-1]-s[i], m[-1]-m[i]])) | estatisticas_de_timbre.ipynb | tiagoft/curso_audio | mit |
Unfortunately this catalog has no metadata. So let's check what kind of services are available. | for service in catalog.services:
print(service.name) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
And what datasets are there? | print("\n".join(catalog.datasets.keys())) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
It looks like model runs as well as satellite and HFR data. One can also check the catalog refs for more information | print("\n".join(catalog.catalog_refs.keys()))
ref = catalog.catalog_refs["Global"]
[value for value in dir(ref) if not value.startswith("__")]
info = """
Href: {}
Name: {}
Title: {}
""".format(
ref.href, ref.name, ref.title
)
print(info) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
The follow method navigates to that catalog ref and returns a new siphon.catalog.TDSCatalog object for that part of the THREDDS catalog. | cat = ref.follow()
print(type(cat)) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
That makes it easier to explore a small subset of the datasets available in the catalog.
Here are the data from the Global subset. | print("\n".join(cat.datasets.keys())) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
Let's extract the Global 1-km Sea Surface Temperature dataset from the global ref. | dataset = "Global 1-km Sea Surface Temperature (G1SST)"
ds = cat.datasets[dataset]
ds.name, ds.url_path | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
Siphon has a ncss (NetCDF subset service) access, here is a quote from the documentation:
This module contains code to support making data requests to
the NetCDF subset service (NCSS) on a THREDDS Data Server (TDS). This includes
forming proper queries as well as parsing the returned data.
Let's check if the catalog ... | for name, ds in catalog.datasets.items():
if ds.access_urls:
print(name) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
All access_urls returned empty.... Maybe that is just a metadata issue because there is NetcdfSubset access when navigating in the webpage. | from IPython.display import HTML
iframe = (
'<iframe src="{src}" width="800" height="550" style="border:none;"></iframe>'.format
)
url = "https://thredds.cencoos.org/thredds/catalog.html?dataset=G1_SST_US_WEST_COAST"
HTML(iframe(src=url)) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
To finish the post let's check if there is any WMS service available and overlay the data in a slippy (interactive) map. | services = [service for service in catalog.services if service.name == "wms"]
services | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
Found only one, let's tease that out and check the URL. | service = services[0]
url = service.base
url | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
OWSLib helps to inspect the available layers before plotting. Here we will get the first layer that has G1_SST_US_WEST_COAST on it.
Note, however, we are skipping the discovery step of the wms information and hard-coding it instead.
That is to save time because parsing the URL http://pdx.axiomalaska.com/ncWMS/wms takes... | from owslib.wms import WebMapService
if False:
web_map_services = WebMapService(url)
layer = [
key for key in web_map_services.contents.keys() if "G1_SST_US_WEST_COAST" in key
][0]
wms = web_map_services.contents[layer]
title = wms.title
lon = (wms.boundingBox[0] + wms.boundingBox[2]) ... | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
Last but not least a static image for the page thumbnail. | from IPython.display import Image
Image(m._to_png()) | notebooks/2017-01-18-siphon-explore-thredds.ipynb | ioos/notebooks_demos | mit |
Explore the Data
Play around with view_sentence_range to view different parts of the data. | view_sentence_range = (1000, 1010)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene ... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dict... | import numpy as np
import problem_unittests as tests
from collections import Counter
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
# TODO: Implement Function... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to token... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
# TODO: Implement Function
token_lookup_dict = {
"." : "||PERIOD||",
"," : "||COMMA||",
"\"" : "||QUOTATI... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following the tuple (... | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
input = tf.placeholder(tf.int32,[None,None], name='input')
targets = tf.placeholder(tf.int32,[None,None], name='targets')
learning_rate = tf.placeholder(tf.f... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the follo... | def get_init_cell(batch_size, rnn_size, keep_prob = 0.5, num_layers = 1):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
# TODO: Implement Function
lstm = tf.contrib.rnn.BasicLSTM... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence. | def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""
embedding = tf.Varia... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState) | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
output,final_state = tf.nn.dynamic_rnn(cell,inputs,dtype=tf.float32)
final_state = tf.identity(final_state,"final_state")
... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number... | def build_nn(cell, rnn_size, input_data, vocab_size):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:return: Tuple (Logits, FinalState)
"""
#get embeddings
embed_layer = ge... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- Th... | #%pdb
def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
# TODO: Implemen... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the ... | # Number of Epochs
num_epochs = 150
# Batch Size
batch_size = 64
# RNN Size
rnn_size = 512
# Sequence Length
seq_length = 16
# Learning Rate
learning_rate = 0.001
# Show stats for every n number of batches
show_every_n_batches = 50
#adding keep prob
keep_prob = 0.8
#adding number of LSTM layers
num_layers = 1
"""
DON'... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Build the Graph
Build the graph using the neural network you implemented. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
from tensorflow.contrib import seq2seq
train_graph = tf.Graph()
with train_graph.as_default():
vocab_size = len(int_to_vocab)
input_text, targets, lr = get_inputs()
input_data_shape = tf.shape(input_text)
cell, initial_state = get_init_cell(input_data_shape[0]... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Choose Word
Implement the pick_word() function to select the next word using probabilities. | def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Generate TV Script
This will generate the TV script for you. Set gen_length to the length of TV script you want to generate. | gen_length = 500
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'moe_szyslak'
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_dir + '.meta')
loa... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-checkpoint.ipynb | mintcloud/deep-learning | mit |
Import data from Google Clod Storage
In this section we'll read some ten years' worth of AAPL stock data into a Pandas dataframe. We want to modify the dataframe such that it represents a time series. This is achieved by setting the date as the index. | df = pd.read_csv('gs://cloud-training/ai4f/AAPL10Y.csv')
df['date'] = pd.to_datetime(df['date'])
df.sort_values('date', inplace=True)
df.set_index('date', inplace=True)
print(df.shape)
df.head() | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Prepare data for ARIMA
The first step in our preparation is to resample the data such that stock closing prices are aggregated on a weekly basis. | df_week = df.resample('w').mean()
df_week = df_week[['close']]
df_week.head() | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Let's create a column for weekly returns. Take the log to of the returns to normalize large fluctuations. | df_week['weekly_ret'] = np.log(df_week['close']).diff()
df_week.head()
# drop null rows
df_week.dropna(inplace=True)
df_week.weekly_ret.plot(kind='line', figsize=(12, 6));
udiff = df_week.drop(['close'], axis=1)
udiff.head() | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Test for stationarity of the udiff series
Time series are stationary if they do not contain trends or seasonal swings. The Dickey-Fuller test can be used to test for stationarity. | import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
rolmean = udiff.rolling(20).mean()
rolstd = udiff.rolling(20).std()
plt.figure(figsize=(12, 6))
orig = plt.plot(udiff, color='blue', label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd, color='b... | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
With a p-value < 0.05, we can reject the null hypotehsis. This data set is stationary.
ACF and PACF Charts
Making autocorrelation and partial autocorrelation charts help us choose hyperparameters for the ARIMA model.
The ACF gives us a measure of how much each "y" value is correlated to the previous n "y" values prior.... | from statsmodels.graphics.tsaplots import plot_acf
# the autocorrelation chart provides just the correlation at increasing lags
fig, ax = plt.subplots(figsize=(12,5))
plot_acf(udiff.values, lags=10, ax=ax)
plt.show()
from statsmodels.graphics.tsaplots import plot_pacf
fig, ax = plt.subplots(figsize=(12,5))
plot_pacf... | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
The table below summarizes the patterns of the ACF and PACF.
<img src="../imgs/How_to_Read_PACF_ACF.jpg" alt="drawing" width="300" height="300"/>
The above chart shows that reading PACF gives us a lag "p" = 3 and reading ACF gives us a lag "q" of 1. Let's Use Statsmodel's ARMA with those parameters to build a model. Th... | from statsmodels.tsa.arima.model import ARIMA
# Notice that you have to use udiff - the differenced data rather than the original data.
ar1 = ARIMA(udiff.values, order = (3, 0,1)).fit()
ar1.summary() | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Our model doesn't do a good job predicting variance in the original data (peaks and valleys). | plt.figure(figsize=(12, 8))
plt.plot(udiff.values, color='blue')
preds = ar1.fittedvalues
plt.plot(preds, color='red')
plt.show() | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Let's make a forecast 2 weeks ahead: | steps = 2
forecast = ar1.forecast(steps=steps)
plt.figure(figsize=(12, 8))
plt.plot(udiff.values, color='blue')
preds = ar1.fittedvalues
plt.plot(preds, color='red')
plt.plot(pd.DataFrame(np.array([preds[-1],forecast[0]]).T,index=range(len(udiff.values)+1, len(udiff.values)+3)), color='green')
plt.plot(pd.DataFrame... | courses/ai-for-finance/solution/arima_model.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
练习:数据探索
首先我们对数据集进行一个粗略的探索,我们将看看每一个类别里会有多少被调查者?并且告诉我们这些里面多大比例是年收入大于50,000美元的。在下面的代码单元中,你将需要计算以下量:
总的记录数量,'n_records'
年收入大于50,000美元的人数,'n_greater_50k'.
年收入最多为50,000美元的人数 'n_at_most_50k'.
年收入大于50,000美元的人所占的比例, 'greater_percent'.
提示: 您可能需要查看上面的生成的表,以了解'income'条目的格式是什么样的。 | # TODO:总的记录数
n_records = len(data)
# TODO:被调查者的收入大于$50,000的人数
n_greater_50k = len(data[data['income']=='>50K'])
# TODO:被调查者的收入最多为$50,000的人数
n_at_most_50k = len(data[data['income']=='<=50K'])
# TODO:被调查者收入大于$50,000所占的比例
greater_percent = n_greater_50k / float(n_records) * 100
# 打印结果
print "Total number of records: {... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
准备数据
在数据能够被作为输入提供给机器学习算法之前,它经常需要被清洗,格式化,和重新组织 - 这通常被叫做预处理。幸运的是,对于这个数据集,没有我们必须处理的无效或丢失的条目,然而,由于某一些特征存在的特性我们必须进行一定的调整。这个预处理都可以极大地帮助我们提升几乎所有的学习算法的结果和预测能力。
获得特征和标签
income 列是我们需要的标签,记录一个人的年收入是否高于50K。 因此我们应该把他从数据中剥离出来,单独存放。 | # 将数据切分成特征和对应的标签
income_raw = data['income']
features_raw = data.drop('income', axis = 1) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
转换倾斜的连续特征
一个数据集有时可能包含至少一个靠近某个数字的特征,但有时也会有一些相对来说存在极大值或者极小值的不平凡分布的的特征。算法对这种分布的数据会十分敏感,并且如果这种数据没有能够很好地规一化处理会使得算法表现不佳。在人口普查数据集的两个特征符合这个描述:'capital-gain'和'capital-loss'。
运行下面的代码单元以创建一个关于这两个特征的条形图。请注意当前的值的范围和它们是如何分布的。 | # 可视化 'capital-gain'和'capital-loss' 两个特征
vs.distribution(features_raw) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
对于高度倾斜分布的特征如'capital-gain'和'capital-loss',常见的做法是对数据施加一个<a href="https://en.wikipedia.org/wiki/Data_transformation_(statistics)">对数转换</a>,将数据转换成对数,这样非常大和非常小的值不会对学习算法产生负面的影响。并且使用对数变换显著降低了由于异常值所造成的数据范围异常。但是在应用这个变换时必须小心:因为0的对数是没有定义的,所以我们必须先将数据处理成一个比0稍微大一点的数以成功完成对数转换。
运行下面的代码单元来执行数据的转换和可视化结果。再次,注意值的范围和它们是如何分布的。 | # 对于倾斜的数据使用Log转换
skewed = ['capital-gain', 'capital-loss']
features_raw[skewed] = data[skewed].apply(lambda x: np.log(x + 1))
# 可视化对数转换后 'capital-gain'和'capital-loss' 两个特征
vs.distribution(features_raw, transformed = True) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
规一化数字特征
除了对于高度倾斜的特征施加转换,对数值特征施加一些形式的缩放通常会是一个好的习惯。在数据上面施加一个缩放并不会改变数据分布的形式(比如上面说的'capital-gain' or 'capital-loss');但是,规一化保证了每一个特征在使用监督学习器的时候能够被平等的对待。注意一旦使用了缩放,观察数据的原始形式不再具有它本来的意义了,就像下面的例子展示的。
运行下面的代码单元来规一化每一个数字特征。我们将使用sklearn.preprocessing.MinMaxScaler来完成这个任务。 | from sklearn.preprocessing import MinMaxScaler
# 初始化一个 scaler,并将它施加到特征上
scaler = MinMaxScaler()
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_raw[numerical] = scaler.fit_transform(data[numerical])
# 显示一个经过缩放的样例记录
display(features_raw.head(n = 1)) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
练习:数据预处理
从上面的数据探索中的表中,我们可以看到有几个属性的每一条记录都是非数字的。通常情况下,学习算法期望输入是数字的,这要求非数字的特征(称为类别变量)被转换。转换类别变量的一种流行的方法是使用独热编码方案。独热编码为每一个非数字特征的每一个可能的类别创建一个_“虚拟”_变量。例如,假设someFeature有三个可能的取值A,B或者C,。我们将把这个特征编码成someFeature_A, someFeature_B和someFeature_C.
| 特征X | | 特征X_A | 特征X_B | 特征X_C |
| :-: | ... | # TODO:使用pandas.get_dummies()对'features_raw'数据进行独热编码
features = pd.get_dummies(features_raw)
# TODO:将'income_raw'编码成数字值
income = income_raw.map(lambda x: 0 if x == '<=50K' else 1)
# print income.head(n=9)
# 打印经过独热编码之后的特征数量
encoded = list(features.columns)
print "{} total features after one-hot encoding.".format(len(... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
混洗和切分数据
现在所有的 类别变量 已被转换成数值特征,而且所有的数值特征已被规一化。和我们一般情况下做的一样,我们现在将数据(包括特征和它们的标签)切分成训练和测试集。其中80%的数据将用于训练和20%的数据用于测试。然后再进一步把训练数据分为训练集和验证集,用来选择和优化模型。
运行下面的代码单元来完成切分。 | # 导入 train_test_split
from sklearn.model_selection import train_test_split
# 将'features'和'income'数据切分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, income, test_size = 0.2, random_state = 0,
stratify = income)
# 将'X_train'和'y_train'进一步切分为训练集和验... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
评价模型性能
在这一部分中,我们将尝试四种不同的算法,并确定哪一个能够最好地建模数据。四种算法包含一个天真的预测器 和三个你选择的监督学习器。
评价方法和朴素的预测器
CharityML通过他们的研究人员知道被调查者的年收入大于\$50,000最有可能向他们捐款。因为这个原因CharityML对于准确预测谁能够获得\$50,000以上收入尤其有兴趣。这样看起来使用准确率作为评价模型的标准是合适的。另外,把没有收入大于\$50,000的人识别成年收入大于\$50,000对于CharityML来说是有害的,因为他想要找到的是有意愿捐款的用户。这样,我们期望的模型具有准确预测那些能够年收入大于\$50,000的能力比模型去查全这些被调查者... | #不能使用scikit-learn,你需要根据公式自己实现相关计算。
# 不知道这里是不是将y_val传过来就可以了,请指导下
income_pred = y_val.apply(lambda x : 1)
TP = sum(map(lambda x,y:1 if x==1 and y==1 else 0,y_val,income_pred))
FN = sum(map(lambda x,y:1 if x==1 and y==0 else 0,y_val,income_pred))
FP = sum(map(lambda x,y:1 if x==0 and y==1 else 0,y_val,income_pred))
TN ... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
监督学习模型
问题 2 - 模型应用
你能够在 scikit-learn 中选择以下监督学习模型
- 高斯朴素贝叶斯 (GaussianNB)
- 决策树 (DecisionTree)
- 集成方法 (Bagging, AdaBoost, Random Forest, Gradient Boosting)
- K近邻 (K Nearest Neighbors)
- 随机梯度下降分类器 (SGDC)
- 支撑向量机 (SVM)
- Logistic回归(LogisticRegression)
从上面的监督学习模型中选择三个适合我们这个问题的模型,并回答相应问题。
模型1
模型名称
回答:决策树
描述一个该模型在真实世界的一个应用场景。... | # TODO:从sklearn中导入两个评价指标 - fbeta_score和accuracy_score
from sklearn.metrics import fbeta_score, accuracy_score
def train_predict(learner, sample_size, X_train, y_train, X_val, y_val):
'''
inputs:
- learner: the learning algorithm to be trained and predicted on
- sample_size: the size of samples (... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
练习:初始模型的评估
在下面的代码单元中,您将需要实现以下功能:
- 导入你在前面讨论的三个监督学习模型。
- 初始化三个模型并存储在'clf_A','clf_B'和'clf_C'中。
- 使用模型的默认参数值,在接下来的部分中你将需要对某一个模型的参数进行调整。
- 设置random_state (如果有这个参数)。
- 计算1%, 10%, 100%的训练数据分别对应多少个数据点,并将这些值存储在'samples_1', 'samples_10', 'samples_100'中
注意:取决于你选择的算法,下面实现的代码可能需要一些时间来运行! | # TODO:从sklearn中导入三个监督学习模型
from sklearn import tree
from sklearn import svm
from sklearn.neural_network import MLPClassifier
# TODO:初始化三个模型
clf_A = tree.DecisionTreeClassifier(random_state=1)
clf_B = svm.SVC(random_state=1)
clf_C = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)
# T... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
提高效果
在这最后一节中,您将从三个有监督的学习模型中选择 最好的 模型来使用学生数据。你将在整个训练集(X_train和y_train)上使用网格搜索优化至少调节一个参数以获得一个比没有调节之前更好的 F-score。
问题 3 - 选择最佳的模型
基于你前面做的评价,用一到两段话向 CharityML 解释这三个模型中哪一个对于判断被调查者的年收入大于 \$50,000 是最合适的。
提示:你的答案应该包括评价指标,预测/训练时间,以及该算法是否适合这里的数据。
回答:
出乎意料,神经网络的各项指标竟然是最好,训练时间短,在测试集上的准确率和FScrore都是三个算法中最高的。
算法适用性这边理解比较浅,请... | # TODO:导入'GridSearchCV', 'make_scorer'和其他一些需要的库
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import fbeta_score, make_scorer
from sklearn.neural_network import MLPClassifier
# TODO:初始化分类器
clf = MLPClassifier(alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)
# TODO:创建你希望调节的参数列表
parameters = {'s... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
问题 5 - 最终模型评估
你的最优模型在测试数据上的准确率和 F-score 是多少?这些分数比没有优化的模型好还是差?你优化的结果相比于你在问题 1中得到的天真预测器怎么样?
注意:请在下面的表格中填写你的结果,然后在答案框中提供讨论。
结果:
| 评价指标 | 天真预测器 | 未优化的模型 | 优化的模型 |
| :------------: | :-----------------: | :---------------: | :-------------: |
| 准确率 | 0.2 | 0.8512 ... | # TODO:导入一个有'feature_importances_'的监督学习模型
from sklearn.ensemble import AdaBoostClassifier
# TODO:在训练集上训练一个监督学习模型
model = AdaBoostClassifier(random_state=0,n_estimators=500).fit(X_train, y_train)
# TODO: 提取特征重要性
importances = model.feature_importances_
# 绘图
vs.feature_plot(importances, X_train, y_train) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
问题 7 - 提取特征重要性
观察上面创建的展示五个用于预测被调查者年收入是否大于\$50,000最相关的特征的可视化图像。
这五个特征的权重加起来是否超过了0.5?<br>
这五个特征和你在问题 6中讨论的特征比较怎么样?<br>
如果说你的答案和这里的相近,那么这个可视化怎样佐证了你的想法?<br>
如果你的选择不相近,那么为什么你觉得这些特征更加相关?
回答:超过了
有些相似,但是整体不准确
我选取的特征,一个是一些基本属性,而且很有可能影响其收入或同理心,但是数据表现的却十分冷酷,是否捐款和赚钱花钱有最大的关系。
特征选择
如果我们只是用可用特征的一个子集的话模型表现会怎么样?通过使用更少的特征来训练,在评价指标的角度来看我... | # 导入克隆模型的功能
from sklearn.base import clone
# 减小特征空间
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_val_reduced = X_val[X_val.columns.values[(np.argsort(importances)[::-1])[:5]]]
# 在前面的网格搜索的基础上训练一个“最好的”模型
clf_on_reduced = (clone(best_clf)).fit(X_train_reduced, y_train)
# 做一个新... | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
问题 8 - 特征选择的影响
最终模型在只是用五个特征的数据上和使用所有的特征数据上的 F-score 和准确率相比怎么样?
如果训练时间是一个要考虑的因素,你会考虑使用部分特征的数据作为你的训练集吗?
回答:均有下降
如果在数据比较大、硬件资源比较匮乏的时候,我会考虑使用,因为选取主要特征的方法会极大提高训练速度
但是再中小型数据或者说硬件资源足够时,我会尽量保证其准确性,一个良好准确的模型的训练时间损耗是值得的
问题 9 - 在测试集上测试你的模型
终于到了测试的时候,记住,测试集只能用一次。
使用你最有信心的模型,在测试集上测试,计算出准确率和 F-score。
简述你选择这个模型的原因,并分析测试结果 | #TODO test your model on testing data and report accuracy and F score
final_predictions = best_clf.predict(X_test)
print "最终准确率: {:.4f}".format(accuracy_score(y_test, final_predictions))
print "最终F-Score: {:.4f}".format(fbeta_score(y_test, final_predictions, beta = 0.5)) | Project2/finding_donors.ipynb | RainFool/Udacity_Anwser_RainFool | mit |
Dear professor Denoyer...
Warning
This is an early version of our entry for the Kaggle challenge
It's still very messy and we send it because we forgot that we had to submit our progress step by step...
To summarize our goal, we plan to use a RNN to take advantage of the sequential data | # from __future__ import exam_success
from __future__ import absolute_import
from __future__ import print_function
%matplotlib inline
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import random
import pandas as pd
import scipy.stats as stats
# Sk cheats
from sklearn.cross_val... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
13.765.202 lines in train.csv
8.022.757 lines in test.csv
Reduced to
10.000
5.000 | %%time
filename = "data/reduced_train_100000.csv"
#filename = "data/reduced_test_100000.csv"
raw = pd.read_csv(filename)
raw = raw.set_index('Id')
#train = train.dropna()
l = float(len(raw["minutes_past"]))
comp = []
for i in raw.columns:
#print(raw"%.03f, %s"%(1-train[i].isnull().sum()/l , i) )
comp.append([1... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
verifier val aberantes sur labels | raw.head(20)
raw["Expected"].describe() | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Get rid of Nan value for now | #train_clean = train[[not i for i in np.isnan(train["Ref_5x5_10th"])]] | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Forums indicate that a higher than 1m rainfall is probably an error. Which is quite understandable. We filter that out | raw = raw[raw['Expected'] < 1000]
raw['Expected'].describe()
split = 0.2
train = raw.tail(int(len(raw)*1-split))
test = raw.tail(int(len(raw)*split)) | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
#columns = [u'minutes_past', u'radardist_km', u'Ref', u'Ref_5x5_10th',
# u'Ref_5x5_50th', u'Ref_5x5_90th', u'RefComposite',
# u'RefComposite_5x5_10th', u'RefComposite_5x5_50th',
# u'RefComposite_5x5_90th', u'RhoHV', u'RhoHV_5x5_10th',
# u'RhoHV_5x5_50th', u'RhoHV_5x5_90th', u'Zdr', u'Zdr_5x5_10t... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 | |
t = []
for i in XX:
t.append(np.count_nonzero(~np.isnan(i)) / float(i.size))
pd.DataFrame(np.array(t)).describe() | XX = []
for i in X:
nm = np.nanmean(i,0)
for idx,j in enumerate(nm):
if np.isnan(j):
nm[idx]=global_means[idx]
XX.append(np.array(nm))
XX = [np.array(t).mean(0) for t in X]
split = 0.2
ps = int(len(XX) * (1-split))
X_train = XX[:ps]
y_train = y[:ps]
X_test = XX[ps:]
y_test = y[ps:]
et... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
def marshall_palmer(ref, minutes_past):
#print("Estimating rainfall from {0} observations".format(len(minutes_past)))
# how long is each observation valid?
valid_time = np.zeros_like(minutes_past)
valid_time[0] = minutes_past.iloc[0]
for n in xrange(1, len(minutes_past)):
valid_time[n] = min... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 | |
Memento (mauri) | etreg = ExtraTreesRegressor(n_estimators=100, max_depth=None, min_samples_split=1, random_state=0)
"""
columns = train_clean.columns
columns = ["minutes_past","radardist_km","Ref","Ref_5x5_10th", "Ref_5x5_50th"]
columns = [u'Id', u'minutes_past', u'radardist_km', u'Ref', u'Ref_5x5_10th',
u'Ref_5x5_50th', u'Ref_... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Submit | filename = "data/reduced_test_5000.csv"
test = pd.read_csv(filename)
columns = [u'minutes_past', u'radardist_km', u'Ref', u'Ref_5x5_10th',
u'Ref_5x5_50th', u'Ref_5x5_90th', u'RefComposite',
u'RefComposite_5x5_10th', u'RefComposite_5x5_50th',
u'RefComposite_5x5_90th', u'RhoHV', u'RhoHV_5x5_10th',
... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
RNN | import pandas as pd
from random import random
flow = (list(range(1,10,1)) + list(range(10,1,-1)))*1000
pdata = pd.DataFrame({"a":flow, "b":flow})
pdata.b = pdata.b.shift(9)
data = pdata.iloc[10:] * random() # some noise
#columns = [u'minutes_past', u'radardist_km', u'Ref', u'Ref_5x5_10th',
# u'Ref_5... | FDMS/TME3/Kaggle_rain-Copy4_from2.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Generate x- and y-values. | x2 = np.arange(100)
data = np.arange(1,40,5)
linear = np.arange(100)
square = [v * v for v in np.arange(0,10,0.1)]
#-- retrieve maximum size of plotting data
maxdim = max(len(data),len(linear),len(square))
#-- create 2D arrays to hold 1D arrays above
y = -999.*np.ones((3,maxdim),'f') #-- assign y... | Visualization/PyNGL/PyEarthScience_xy_PyNGL.ipynb | KMFleischer/PyEarthScience | mit |
Draw data, set title and axis labels. | #-- open a workstation
wkres = Ngl.Resources() #-- generate an res object for workstation
wks = Ngl.open_wks("png","plot_xy_simple_PyNGL",wkres)
#-- set resources
res = Ngl.Resources() #-- generate an res object for plot
res.tiMainString... | Visualization/PyNGL/PyEarthScience_xy_PyNGL.ipynb | KMFleischer/PyEarthScience | mit |
Show the plot in this notebook. | from IPython.display import Image
Image(filename='plot_xy_simple_PyNGL.png') | Visualization/PyNGL/PyEarthScience_xy_PyNGL.ipynb | KMFleischer/PyEarthScience | mit |
Numerical Optimization - Root Finding
What is $x$ in
$$\cos (x) = x$$
To use a root-finding method, we must make our equation have one side be 0.
$$\cos (x) - x = 0$$
Newton's Method - For finding Roots | from scipy.optimize import newton
root = newton(lambda x: np.cos(x) - x, x0=0)
print(root, np.cos(root) - root) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
$$x_{i+1} = x_i - \frac{f(x_i)}{f'(x_i)}$$
This method, like all this unit are iterative. This is modifiable by you, either through choosing tolerance, or maximum iterations. The functions have sensible defaults | root = newton(lambda x: np.cos(x) - x, x0=0, tol=1e-3)
print(root, np.cos(root) - root)
root = newton(lambda x: np.cos(x) - x, x0=0, tol=1e-3, maxiter=5)
print(root, np.cos(root) - root) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Newton's Method
Use root instead, this is just for instructional purposes. root is better
Type: Root Finding
Discrete/Continuous: Continuous
Dimensions: 1
Derivative: optional
Non-Convex: not recommended
Python: newton
Let's try to solve a more interesting equation with Newton's method!
$$ \int_0^x e^{-s^2}\,ds = \frac... | #Note: this code is intentionally really bad
from scipy.integrate import quad
def equation(x):
return quad(lambda s: np.exp(-s**2), 0, x)
root = newton(equation, x0=0) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Steps for Debugging Code
Correct any Python errors
Restart the Kernel
Correct any Python errors
Print to discover logical errors
Most Common Mistakes
Copy-Pasta leaving in old variables
Mixing Numpy arrays and for loops
Forgetting order of function args and return values
Review of Functions
For functions like quad,... | def version_1(x):
return x**2 - 3 *x + 2
version_2 = lambda x: x ** 2 - 3 *x + 2
np_version = np.vectorize(version_1)
print(version_1(3.))
print(version_2(3.))
some_threes = np.zeros(10)
some_threes[:] = 3.0 # -> Notice how we don't replace the numpy array with 3, but instead make all elements in it equal to th... | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
$$\int_{\pi}^x \sin^2(s)\,ds$$ | from scipy.integrate import quad
import numpy as np
from math import pi
def integrate_sin2(x):
ans, err = quad(lambda s: np.sin(s) ** 2, pi, x)
return ans
print(integrate_sin2(2 * pi)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
2 Vectors, $\vec{x}$ and $\vec{y}$, where one component of $\vec{x}$ is changing and we want to know the distance between the two vectors. | from math import sqrt
def distance(x, y):
sum_sq = np.sum((x - y)**2)
return sqrt(sum_sq)
def my_distance(s):
x = np.zeros(3)
y = np.zeros(3)
x[0] = 2.0
x[1] = s
x[2] = -3.5
y[0] = 1.0
y[1] = -3.0
y[2] = 0.0
return distance(x, y)
print(my_distance(1)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Incorrect Examples
No Return Value | def version_1(x):
x**2 - 3 *x + 2
print(version_1(3.)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Bad Return Value | def integrate_sin2(x):
return quad(lambda s: np.sin(s) ** 2, pi, x)
print(integrate_sin2(2 * pi)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Too many arguments | def distance(x, y):
sum_sq = np.sum((x - y)**2)
return sqrt(sum_sq)
print(distance(1)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Let's return to our example from above:
$$ \int_0^x e^{-s^2}\,ds = \frac{1}{2}$$
Find $x$ | #note still wrong
def equation(x):
ans, err = quad(lambda s: np.exp(-s**2), 0, x)
return ans
root = newton(equation, x0=0)
print(root)
equation(root) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
We forgot to rearrange the equation to be equal to $0$ | root = newton(lambda x: equation(x) - 0.5, x0=0)
print(root, equation(root)) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Scope
Scope means the set of variables and functions which are defined and accessible in your code | x = 4
y = 2
#Right now, there is x,y and all other functions/variables defined or imported above in the scope | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Scopes nest | x = 4
y = 2
#Here, I have x and y in scope
def scope_example():
z = 2
#Here, I have x,y and z in scope
#Here I again have only x and y in scope
x = 4
y = 2
print(y,"Before function")
def scope_example():
y = 25 #This is a new version of y that exists only in this scope
print(y, "Inside function")... | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Things to remember about scope:
Scopes nest, so that you can access things above your scope
You can modify variables from any scope you can see, but ones you create disappear outside of the scope
Returning to Optimization
Applications of Optimization
Solving non-linear equations
Solving systems of equations
Optimizi... | def two_well(x):
if x < 0.125:
return (x + 2) ** 2
if x >= 0.125:
return (x - 2) ** 2 + 1
np_two_well = np.vectorize(two_well)
x = np.linspace(-4, 4, 1000)
plt.plot(x, np_two_well(x))
plt.show() | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
BFGS Optimization - Minimization
Broyden–Fletcher–Goldfarb–Shanno
BFGS
Type: Minimization
Discrete/Continuous: Continuous
Dimensions: N
Derivative: optional
Non-Convex: not recommended
Python: minimize if no constraints or bounds are given
Nomenclature
In optimization, you have a function called the objective function.... | def obj(x):
return x**2
x = np.linspace(-1,1,100)
plt.plot(x, obj(x))
plt.show()
from scipy.optimize import minimize
minimize(obj, x0=3) | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Minimize Return value
fun: The value of the function at the minimum
hess_inv: The inverse of the the Hessian
jac: The value of the Jacobian
message: A string describing what happened
nfev: Number of function evaluations
nit: Number of iterations of the x point
njev: Number of times it computed t... | def f(x):
return ((x-4)**2)/2+((x-2)**2)/4
x = np.linspace(-10, 10, 100)
plt.plot(x, f(x))
plt.show()
result = minimize(f, x0=0)
print(f'the minimum value occurs at {result.x} and is {result.fun}') | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
A bad objective function
Minimize the following:
$$
f(x) = \frac{(x - 4)} { 2 }
$$
The minimum is at $-\infty$! | result = minimize(lambda x: (x - 4) / 2, x0=0)
print(f'the minimum value occurs at {result.x} and is {result.fun}') | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
A good objective function but bad x0
Minimize the following function
$$4 \left[ r^{-12} - r^{-6}\right]$$ | result = minimize(lambda r: 4 * (r**(-12) - r**(-6)), x0=0)
print(f'the minimum is at {result.x}') | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Our initial value was not in the domain! | r = np.linspace(0.9, 2, 100)
y = 4 * (r**(-12) - r**(-6))
plt.plot(r, y)
plt.show()
result = minimize(lambda r: 4 * (r**(-12) - r**(-6)), x0=1)
print(f'the minimum is at {result.x} and its value is {result.fun}') | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Maximizing
In order to maximzie a function, just add a minus sign
Maximize the following function:
$$
-\left[x - \cos(x)\right]^2
$$ | #place - sign to make it a maxmimization problem
result = minimize(lambda x: (x - np.cos(x))**2, x0=1)
print(f'the maximum is at {result.x}') | unit_11/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.