markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Example: normalizing features | from tensorflow.keras.layers import Normalization
# Example image data, with values in the [0, 255] range
training_data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype("float32")
normalizer = Normalization(axis=-1)
normalizer.adapt(training_data)
normalized_data = normalizer(training_data)
print("var: %.4... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Example: rescaling & center-cropping images
Both the Rescaling layer and the CenterCrop layer are stateless, so it isn't
necessary to call adapt() in this case. | from tensorflow.keras.layers import CenterCrop
from tensorflow.keras.layers import Rescaling
# Example image data, with values in the [0, 255] range
training_data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype("float32")
cropper = CenterCrop(height=150, width=150)
scaler = Rescaling(scale=1.0 / 255)
outp... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Building models with the Keras Functional API
A "layer" is a simple input-output transformation (such as the scaling &
center-cropping transformations above). For instance, here's a linear projection layer
that maps its inputs to a 16-dimensional feature space:
python
dense = keras.layers.Dense(units=16)
A "model" is ... | # Let's say we expect our inputs to be RGB images of arbitrary size
inputs = keras.Input(shape=(None, None, 3)) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
After defining your input(s), you can chain layer transformations on top of your inputs,
until your final output: | from tensorflow.keras import layers
# Center-crop images to 150x150
x = CenterCrop(height=150, width=150)(inputs)
# Rescale images to [0, 1]
x = Rescaling(scale=1.0 / 255)(x)
# Apply some convolution and pooling layers
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x)
x = layers.MaxPooling2D(poo... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Once you have defined the directed acyclic graph of layers that turns your input(s) into
your outputs, instantiate a Model object: | model = keras.Model(inputs=inputs, outputs=outputs) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
This model behaves basically like a bigger layer. You can call it on batches of data, like
this: | data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype("float32")
processed_data = model(data)
print(processed_data.shape) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
You can print a summary of how your data gets transformed at each stage of the model.
This is useful for debugging.
Note that the output shape displayed for each layer includes the batch size. Here
the batch size is None, which indicates our model can process batches of any size. | model.summary() | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
The Functional API also makes it easy to build models that have multiple inputs (for
instance, an image and its metadata) or multiple outputs (for instance, predicting
the class of the image and the likelihood that a user will click on it). For a
deeper dive into what you can do, see our
guide to the Functional API.
T... | # Get the data as Numpy arrays
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Build a simple model
inputs = keras.Input(shape=(28, 28))
x = layers.Rescaling(1.0 / 255)(inputs)
x = layers.Flatten()(x)
x = layers.Dense(128, activation="relu")(x)
x = layers.Dense(128, activation="relu")(x)
outp... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
The fit() call returns a "history" object which records what happened over the course
of training. The history.history dict contains per-epoch timeseries of metrics
values (here we have only one metric, the loss, and one epoch, so we only get a single
scalar): | print(history.history) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
For a detailed overview of how to use fit(), see the
guide to training & evaluation with the built-in Keras methods.
Keeping track of performance metrics
As you're training a model, you want to keep track of metrics such as classification
accuracy, precision, recall, AUC, etc. Besides, you want to monitor these metrics... | model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")],
)
history = model.fit(dataset, epochs=1) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Passing validation data to fit()
You can pass validation data to fit() to monitor your validation loss & validation
metrics. Validation metrics get reported at the end of each epoch. | val_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(batch_size)
history = model.fit(dataset, epochs=1, validation_data=val_dataset) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Using callbacks for checkpointing (and more)
If training goes on for more than a few minutes, it's important to save your model at
regular intervals during training. You can then use your saved models
to restart training in case your training process crashes (this is important for
multi-worker distributed training, si... | loss, acc = model.evaluate(val_dataset) # returns loss and metrics
print("loss: %.2f" % loss)
print("acc: %.2f" % acc) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
You can also generate NumPy arrays of predictions (the activations of the output
layer(s) in the model) via predict(): | predictions = model.predict(val_dataset)
print(predictions.shape) | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Using fit() with a custom training step
By default, fit() is configured for supervised learning. If you need a different
kind of training loop (for instance, a GAN training loop), you
can provide your own implementation of the Model.train_step() method. This is the
method that is repeatedly called during fit().
Metri... | # Example training data, of dtype `string`.
samples = np.array([["This is the 1st sample."], ["And here's the 2nd sample."]])
labels = [[0], [1]]
# Prepare a TextVectorization layer.
vectorizer = TextVectorization(output_mode="int")
vectorizer.adapt(samples)
# Asynchronous preprocessing: the text vectorization is par... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Compare this to doing text vectorization as part of the model: | # Our dataset will yield samples that are strings
dataset = tf.data.Dataset.from_tensor_slices((samples, labels)).batch(2)
# Our model should expect strings as inputs
inputs = keras.Input(shape=(1,), dtype="string")
x = vectorizer(inputs)
x = layers.Embedding(input_dim=10, output_dim=32)(x)
outputs = layers.Dense(1)(x... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Quiz Question. How many reviews contain the word perfect? | len(products[products['contains_perfect']==1])
def get_numpy_data(dataframe, features, label):
dataframe['constant'] = 1
features = ['constant'] + features
features_frame = dataframe[features]
features_matrix = features_frame.as_matrix()
label_sarray = dataframe[label]
label_array = label_sarra... | ml-classification/week-2/Untitled.ipynb | isendel/machine-learning | apache-2.0 |
Quiz Question: How many features are there in the feature_matrix? | feature_matrix.shape
def predict_probability(feature_matrix, coefficients):
score = feature_matrix.dot(coefficients)
predictions = np.apply_along_axis(lambda x: 1/(1+math.exp(-x)), 1, score)
return predictions.reshape((max(predictions.shape), 1))
w = np.ones((194,1))
predict_probability(feature_matrix, w... | ml-classification/week-2/Untitled.ipynb | isendel/machine-learning | apache-2.0 |
Compute derivative of log likelihood with respect to a single coefficient | def feature_derivative(errors, feature):
derivative = errors.transpose().dot(feature)
return derivative
def compute_log_likelihood(feature_matrix, sentiment, coefficients):
indicator = (sentiment==+1)
scores = feature_matrix.dot(coefficients)
lp = np.sum((indicator-1)*scores - np.log(1 + np.exp(-sc... | ml-classification/week-2/Untitled.ipynb | isendel/machine-learning | apache-2.0 |
Quiz question: What is the accuracy of the model on predictions made above? (round to 2 digits of accuracy) | accuracy = len(products[products['sentiment']==products['predictions']])/len(products)
print('Accuracy: %s' % accuracy) | ml-classification/week-2/Untitled.ipynb | isendel/machine-learning | apache-2.0 |
Which words contribute most to positive & negative sentiments | coefficients = list(coefficients[1:]) # exclude intercept
word_coefficient_tuples = [(word, coefficient) for word, coefficient in zip(important_words, coefficients)]
word_coefficient_tuples = sorted(word_coefficient_tuples, key=lambda x:x[1], reverse=True)
word_coefficient_tuples[:10]
sorted(word_coefficient_tuples, ... | ml-classification/week-2/Untitled.ipynb | isendel/machine-learning | apache-2.0 |
aggregate_source - NIST XPS DB
Example: We want to collect all records from the NIST XPS Database and analyze the binding energies. This database has almost 30,000 records, so we have to use aggregate(). | # First, let's aggregate all the nist_xps_db data.
all_entries = mdf.aggregate_sources("nist_xps_db")
print(len(all_entries))
# Now, let's parse out the enery_uncertainty_ev and print the results for analysis.
uncertainties = {}
for record in all_entries:
if record["mdf"]["resource_type"] == "record":
unc ... | docs/examples/Example_Aggregations.ipynb | materials-data-facility/forge | apache-2.0 |
aggregate - Multiple Datasets
Example: We want to analyze how often elements are studied with Gallium (Ga), and what the most frequent elemental pairing is. There are more than 10,000 records containing Gallium data. | # First, let's aggregate everything that has "Ga" in the list of elements.
all_results = mdf.aggregate("material.elements:Ga")
print(len(all_results))
# Now, let's parse out the other elements in each record and keep a running tally to print out.
elements = {}
for record in all_results:
if record["mdf"]["resource_... | docs/examples/Example_Aggregations.ipynb | materials-data-facility/forge | apache-2.0 |
Day 5: Introduction to Linear Regression
Objective
In this challenge, we practice using linear regression techniques. Check out the Resources tab to learn more!
Task
You are given the Math aptitude test (x) scores for a set of students, as well as their respective scores for a Statistics course (y). The students enroll... | # #Python Import Libraries
import sklearn
import numpy as np
arr_x = [i[0] for i in arr_data]
arr_y = [i[1] for i in arr_data]
stats.linregress(arr_x, arr_y)
m, c, r_val, p_val, err = stats.linregress(arr_x, arr_y)
# #y = mx + c
m*80 + c | HackerRank/Intro_to_Statistics/Day_05.ipynb | KartikKannapur/Programming_Challenges | mit |
Load Images from Disk
If the data is too large to put in memory all at once, we can load it batch by
batch into memory from disk with tf.data.Dataset. This
function
can help you build such a tf.data.Dataset for image data.
First, we download the data and extract the files. | dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" # noqa: E501
local_file_path = tf.keras.utils.get_file(
origin=dataset_url, fname="image_data", extract=True
)
# The file is extracted in the same directory as the downloaded file.
local_dir_path = os.path.dirna... | docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
The directory should look like this. Each folder contains the images in the
same class.
flowers_photos/
daisy/
dandelion/
roses/
sunflowers/
tulips/
We can split the data into training and testing as we load them. | batch_size = 32
img_height = 180
img_width = 180
train_data = ak.image_dataset_from_directory(
data_dir,
# Use 20% data as testing data.
validation_split=0.2,
subset="training",
# Set seed to ensure the same split when loading testing data.
seed=123,
image_size=(img_height, img_width),
... | docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
Then we just do one quick demo of AutoKeras to make sure the dataset works. | clf = ak.ImageClassifier(overwrite=True, max_trials=1)
clf.fit(train_data, epochs=1)
print(clf.evaluate(test_data))
| docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
Load Texts from Disk
You can also load text datasets in the same way. | dataset_url = "http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
local_file_path = tf.keras.utils.get_file(
fname="text_data",
origin=dataset_url,
extract=True,
)
# The file is extracted in the same directory as the downloaded file.
local_dir_path = os.path.dirname(local_file_path)
# After ch... | docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
For this dataset, the data is already split into train and test.
We just load them separately. | print(data_dir)
train_data = ak.text_dataset_from_directory(
os.path.join(data_dir, "train"), batch_size=batch_size
)
test_data = ak.text_dataset_from_directory(
os.path.join(data_dir, "test"), shuffle=False, batch_size=batch_size
)
clf = ak.TextClassifier(overwrite=True, max_trials=1)
clf.fit(train_data, epo... | docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
Load Data with Python Generators
If you want to use generators, you can refer to the following code. |
N_BATCHES = 30
BATCH_SIZE = 100
N_FEATURES = 10
def get_data_generator(n_batches, batch_size, n_features):
"""Get a generator returning n_batches random data.
The shape of the data is (batch_size, n_features).
"""
def data_generator():
for _ in range(n_batches * batch_size):
x =... | docs/ipynb/load.ipynb | keras-team/autokeras | apache-2.0 |
Create a requests.Session for holding our oauth token | import requests
s = requests.session()
s.headers['Authorization'] = 'token ' + gh_token | examples/auth_state/gist-nb.ipynb | jupyter/oauthenticator | bsd-3-clause |
Verify that we have the scopes we expect: | r = s.get('https://api.github.com/user')
r.raise_for_status()
r.headers['X-OAuth-Scopes'] | examples/auth_state/gist-nb.ipynb | jupyter/oauthenticator | bsd-3-clause |
Now we can make a gist! | import json
r = s.post('https://api.github.com/gists',
data=json.dumps({
'files': {
'test.md': {
'content': '# JupyterHub gist\n\nThis file was created from JupyterHub.',
},
},
'description': 'test uploading a gist from JupyterHub',
}),
)
r.raise_f... | examples/auth_state/gist-nb.ipynb | jupyter/oauthenticator | bsd-3-clause |
TFP Probabilistic Layers: Regression
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/probability/examples/Probabilistic_Layers_Regression"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a tar... | #@title Import { display-mode: "form" }
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
sns.reset_defaults()
#sns.set_style('whitegrid')
#sns.set_context('talk')
sns.set... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Note: if for some reason you cannot access a GPU, this colab will still work. (Training will just take longer.)
Motivation
Wouldn't it be great if we could use TFP to specify a probabilistic model then simply minimize the negative log-likelihood, i.e., | negloglik = lambda y, rv_y: -rv_y.log_prob(y) | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Well not only is it possible, but this colab shows how! (In context of linear regression problems.) | #@title Synthesize dataset.
w0 = 0.125
b0 = 5.
x_range = [-20, 60]
def load_dataset(n=150, n_tst=150):
np.random.seed(43)
def s(x):
g = (x - x_range[0]) / (x_range[1] - x_range[0])
return 3 * (0.25 + g**2.)
x = (x_range[1] - x_range[0]) * np.random.rand(n) + x_range[0]
eps = np.random.randn(n) * s(x)
... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Case 1: No Uncertainty | # Build model.
model = tf.keras.Sequential([
tf.keras.layers.Dense(1),
tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1)),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=negloglik)
model.fit(x, y, epochs=1000, verbose=False);
# Profit.
[print(np.squeeze(w.... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Case 2: Aleatoric Uncertainty | # Build model.
model = tf.keras.Sequential([
tf.keras.layers.Dense(1 + 1),
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(0.05 * t[...,1:]))),
])
# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01), loss=... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Case 3: Epistemic Uncertainty | # Specify the surrogate posterior over `keras.layers.Dense` `kernel` and `bias`.
def posterior_mean_field(kernel_size, bias_size=0, dtype=None):
n = kernel_size + bias_size
c = np.log(np.expm1(1.))
return tf.keras.Sequential([
tfp.layers.VariableLayer(2 * n, dtype=dtype),
tfp.layers.DistributionLambda... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Case 4: Aleatoric & Epistemic Uncertainty | # Build model.
model = tf.keras.Sequential([
tfp.layers.DenseVariational(1 + 1, posterior_mean_field, prior_trainable, kl_weight=1/x.shape[0]),
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(0.01 * t[...,1:]))),
])
# Do inference.
... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Case 5: Functional Uncertainty | #@title Custom PSD Kernel
class RBFKernelFn(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(RBFKernelFn, self).__init__(**kwargs)
dtype = kwargs.get('dtype', None)
self._amplitude = self.add_variable(
initializer=tf.constant_initializer(0),
dtype=dtype,
nam... | site/en-snapshot/probability/examples/Probabilistic_Layers_Regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
=================================
Decoding sensor space data (MVPA)
=================================
Decoding, a.k.a MVPA or supervised machine learning applied to MEG
data in sensor space. Here the classifier is applied to every time
point. | import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import mne
from mne.datasets import sample
from mne.decoding import (SlidingEstimator, GeneralizingEstimator,
... | 0.15/_downloads/plot_sensors_decoding.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Temporal decoding
We'll use a Logistic Regression for a binary classification as machine
learning model. | # We will train the classifier on all left visual vs auditory trials on MEG
X = epochs.get_data() # MEG signals: n_epochs, n_channels, n_times
y = epochs.events[:, 2] # target: Audio left or right
clf = make_pipeline(StandardScaler(), LogisticRegression())
time_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_... | 0.15/_downloads/plot_sensors_decoding.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The results of these mass univariate analyses can be visualised by plotting
:class:mne.Evoked objects as images (via :class:mne.Evoked.plot_image)
and masking points for significance.
Here, we group channels by Regions of Interest to facilitate localising
effects on the head. | # We need an evoked object to plot the image to be masked
evoked = mne.combine_evoked([long_words.average(), -short_words.average()],
weights='equal') # calculate difference wave
time_unit = dict(time_unit="s")
evoked.plot_joint(title="Long vs. short words", ts_args=time_unit,
... | 0.20/_downloads/2784a8d5822ed9797c0330f973573c10/plot_stats_cluster_erp.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a positive example of the principles that Tufte describes in The Visual Display of Quantitative Information.
Vox
Upshot
538
BuzzFeed
Upload the image for the visualization to this directory and display the im... | # Add your filename and uncomment the following line:
Image(filename='Quartz_death_penalty_chart.0.png') | assignments/assignment04/TheoryAndPracticeEx01.ipynb | enbanuel/phys202-2015-work | mit |
The saver op will enable saving and restoring: | saver = tf.train.Saver() | ch02_basics/Concept06_saving_variables.ipynb | BinRoot/TensorFlow-Book | mit |
Loop through the data and update the spike variable when there is a significant increase: | for i in range(1, len(raw_data)):
if raw_data[i] - raw_data[i-1] > 5:
spikes_val = spikes.eval()
spikes_val[i] = True
updater = tf.assign(spikes, spikes_val)
updater.eval() | ch02_basics/Concept06_saving_variables.ipynb | BinRoot/TensorFlow-Book | mit |
Now, save your variable to disk! | save_path = saver.save(sess, "./spikes.ckpt")
print("spikes data saved in file: %s" % save_path) | ch02_basics/Concept06_saving_variables.ipynb | BinRoot/TensorFlow-Book | mit |
Adieu: | sess.close() | ch02_basics/Concept06_saving_variables.ipynb | BinRoot/TensorFlow-Book | mit |
StockTwits Data Collection
First we will write a function to query the StockTwits API to get up to 30 tweets at a time for a given ticker symbol. The API allows getting only tweets older than some tweet ID, which we need for repeatedly querying the server to get many recent tweets. | # returns python object representation of JSON in response
def get_response(symbol, older_than, retries=5):
url = 'https://api.stocktwits.com/api/2/streams/symbol/%s.json?max=%d' % (symbol, older_than-1)
for _ in range(retries):
response = requests.get(url)
if response.status_code == 200:
... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Now we can write a function to build or extend a dataset of tweets for a given symbol. This works by remembering the oldest ID of tweets we have gotten so far, and using that as an option in the API query to get older tweets. By doing this we can iteratively build up a list of recent tweets for a given symbol ordered f... | # extends the current dataset for a given symbol with more tweets
def get_older_tweets(symbol, num_queries):
path = './data/%s.json' % symbol
if os.path.exists(path):
# extending an existing json file
with open(path, 'r') as f:
data = json.load(f)
if len(data) > 0:
... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Now we fetch data for several ticker symbols. Note that to get all the data, you will have to rerun this cell once an hour multiple times because of API rate limiting. The JSON files will be distributed with this notebook so this cell is only here to show how we originally got the data. | # get some data
# apparently a client can only make 200 requests an hour, so we can't get all the data at once
# make data directory if needed
if not os.path.exists('./data'):
os.mkdir('./data')
symbols = symbols = ['AAPL', 'NVDA', 'TSLA', 'AMD', 'JNUG', 'JDST', 'LABU', 'QCOM', 'INTC', 'DGAZ']
tweets_per_symb... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
The next cell is mainly just for debugging purposes. There is no need to run it. | # check that we're doing the querying and appending correctly without getting duplicates
# and that message IDs are in descending order
symbol = 'NVDA'
with open('./data/%s.json' % symbol, 'r') as f:
data = json.load(f)
S = set()
old_id = 1000000000000
for message in data:
message_id = message['id']
assert ... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Stock Market Data Comparison
Next, we'll extract stock market data for the symbols we're interested in. For the purpose of our experiment, we'll use Yahoo Finance's daily stock data. The API takes in a start date, end date, and stock symbol. | enddate=datetime.now()
startdate=datetime(2015,1,1)
stock_data = get_data_yahoo('AAPL',startdate,enddate)
stock_data['Volume'].plot(legend=True,figsize=(10,4));
stock_data.head()
stock_data['Adj Close'].plot(legend=True,figsize=(10,4)); | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
As you can see, we can quickly and easily pull both volume and closing prices for the dates of interest. This data was useful in exploring the possibility of predicting market performance.
Data Visualization & Exploration
Next, we parsed the JSON data we've collected into a Pandas DataFrame to more easily work with it... | # Function takes in a JSON and returns a Pandas DataFrame for easier operation.
def stocktwits_json_to_df(data, verbose=False):
#data = json.loads(results)
columns = ['id','created_at','username','name','user_id','body','basic_sentiment','reshare_count']
db = pd.DataFrame(index=range(len(data)),columns=col... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We're going to use \$TSLA to visualize data since we have data going back the furthest. We'll now combine these two data sources, so we can generate useful metrics for understanding how StockTwits relates to the stock market over time. | # Load tweets for visualizing data
filename = 'TSLA.json'
path = './tsla_data/%s' % filename
with open(path, 'r') as f:
data = json.load(f)
db = stocktwits_json_to_df(data)
print '%d examples extracted ' % db.shape[0]
enddate = db['created_at'].max()
startdate = db['created_at'].min()
print startdate, enddate
stoc... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We now will combine our datasets. In the process, we also generate statistics related to the total number of bullish/bearish tweets. This is accomplished by grouping tweets by day. We pay attention to the totals and their ratios to each other.
- Mentions: Total number of mentions with our without bullish/bearish labe... | #Counts mentions and bullish/bearish ratio of stock tweets collected
def tweet_metrics(stock_data, stock_tweets):
stock_data['mentions'] = np.zeros(stock_data.shape[0])
stock_data['total_bullish'] = np.zeros(stock_data.shape[0])
stock_data['total_bearish'] = np.zeros(stock_data.shape[0])
stock_data['tot... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Now we can now visualize the results of our analysis. | stock_metrics = tweet_metrics(stock_data, db)
print stock_metrics[['mentions','total_bullish','total_bearish','bull_ratio']] | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Note that Yahoo's Finance data is "delayed" (i.e. It won't show the current day unless the market has closed).
Next, we'll compare our metrics to gain an understand of StockTwits's correlation to the stock market. In our first comparison, we see a clear correlation between the number of mentions and the trading volume.... | stock_metrics[['mentions']].plot(legend=True,figsize=(10,4));
stock_metrics[['Volume']].plot(legend=True,figsize=(10,4)); | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Finally, we'll compare the total closing price to the bullish/bearish predictions of Stock Twits. Here, we see the strong correlation between market and StockTwits begin to breakdown.
There seems to be an abundance of optimism: The majority of labelled tweets are "bullish". Additionally, not all peaks and valleys appe... | stock_metrics[['total_bullish','total_bearish','total_predictions']].plot(legend=True,figsize=(10,4));
stock_metrics[['bull_ratio','bear_ratio']].plot(legend=True,figsize=(10,4));
stock_metrics[['Adj Close']].plot(legend=True,figsize=(10,4)); | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We will next explore the connections between symbols mentioned in the tweets. The function below counts the co-occurrences of symbols mentioned in StockTwits' tweets. | def countcomentions(df):
def getsymbolset(df):
symbols = []
for i, row in df.iterrows():
for symbol in row:
if (pd.notnull(symbol)):
symbols.append(symbol)
return set(symbols)
def getallsymbols(df):
columns = df.columns
... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We see a clear power-law distribution when viewing the histogram of mentions related to Tesla Motors. The vast majority of tweets are mentioned only a few times. | plt.figure(figsize=(10,4))
The sns.distplot(co.loc['TSLA',:], kde=False) | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
The histogram above tells us that the some stocks will have a disproportionate relationship to TSLA. The twenty most commonly co-mentioned tweets are given below.
Unsurprisingly, SolarCity Corporation (SCTY) was listed most commonly. SolarCity was recently in the news due to its decision to merge with Tesla Motors fol... | co.loc['TSLA',co.loc['TSLA',:]>0].sort_values(ascending=False)[:20] | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Very few others even come close to the density of TSLA and SCTY. Those that are mentioned are often in the same segment as Tesla. These are big-name tech stocks: Apple, Amazon, Netflix, Facebook, Google, and Alibaba.
Below is a heatmap of the co-mentions matrix. It is 788 x 788 and focused between 0 & 5. Note that the... | plt.figure(figsize=(45,10))
sns.heatmap(co, xticklabels=False, vmin=0, vmax=5, yticklabels=False, square=True); | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Having successful datamined StockTwits, we explored some of the relationships found in the data. However, we did not find sufficient evidence that stock performance could be predicted by tweets. For these reasons, we shift our focus.
StockTwits provides a remarkably large set of labeled data for training. We explored ... | def get_tweets_and_labels(data):
# filter out messages without a bullish/bearish tag
data = filter(lambda m: m['entities']['sentiment'] != None, data)
# get tweets
tweets = map(lambda m: m['body'], data)
# get labels
def create_label(message):
sentiment = message['entities']['sentiment']... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
The next two cells make functions to create a TF-IDF vectorizer for the tweets and to train a linear SVM classifier to predict bearish or bullish sentiment. | def tfidf_vectorizer(tweets, all_tweets=None):
vectorizer = TfidfVectorizer()
if all_tweets != None:
# use all tweets, including unlabeled, to learn vocab and tfidf weights
vectorizer.fit(all_tweets)
else:
vectorizer.fit(tweets)
return vectorizer
def train_svm(X, y):
model =... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We first create the TF-IDF feature matrix for all of our labeled data. Then we randomly permute it and split 10% off into a held out test set. We also print out the percentage of labeled tweets that are bullish, because the 2 classes are likely not balanced. We want to know how well a classifier that only predicts the ... | vectorizer = tfidf_vectorizer(tweets, all_tweets)
X = vectorizer.transform(tweets)
words = vectorizer.get_feature_names()
y = np.array(labels)
print X.shape
print y.shape
N = X.shape[0]
num_train = int(math.floor(N*0.9))
P = np.random.permutation(N)
X_tr = X[P[:num_train]]
y_tr = y[P[:num_train]]
X_te = X[P[num_train:... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Now it is simple to train the SVM and print our the accuracy for both the training and testing data. | model = train_svm(X_tr, y_tr)
print 'Training set accuracy = %f' % model.score(X_tr, y_tr)
print 'Test set accuracy = %f' % model.score(X_te, y_te) | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
We can see that the classifier does several percent better than just guessing the most common class.
Now that we have a trained SVM, we can use the weights to print out words most indicative of bearish or bullish sentiment. This is because we used a linear SVM, so each weight coefficient corresponds to a column in the ... | weights = np.squeeze(model.coef_)
sorted_weight_indices = np.argsort(weights)
num_words = 30
bearish_indices = sorted_weight_indices[:num_words]
bullish_indices = sorted_weight_indices[-num_words:][::-1]
words = np.array(words)
print 'Bearish words:'
for w in words[bearish_indices]:
print w
print
print 'Bullish wor... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
The results are actually pretty interesting. I'll give a bit of explanation for some of the terms for people who are not familiar with the stock market. If you expect the price of a stock to fall, you can try to make money off it by shorting it or buying a type of option called puts. If the price is falling, you could ... | model = linear_model.LogisticRegression(penalty='l2', C=10.0, class_weight='balanced')
#model = svm.LinearSVC(penalty='l2', loss='hinge', C=1.0, class_weight='balanced')
model.fit(X, y)
with open('./tsla_data/TSLA.json', 'r') as f:
data = json.load(f)[::-1]
def extract_body(m):
return m['body']
def extract_d... | stocktwits_analysis.ipynb | tdrussell/stocktwits_analysis | mit |
Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence fr... | def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionar... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
- model_inputs
- process_decoding_input
- encoding_layer
- decoding_layer_train
- decoding_layer_infer
- decoding_layer
- seq2seq_model
Input
Implement the model_inputs() f... | def model_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate, keep probability)
"""
input_ = tf.placeholder(shape=(None, None), dtype=tf.int32, name='input')
targets = tf.placeholder(shape=(None, None), dtype=tf.int32, name='... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Process Decoding Input
Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the begining of each batch. | def process_decoding_input(target_data, target_vocab_to_int, batch_size):
"""
Preprocess target data for dencoding
:param target_data: Target Placehoder
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param batch_size: Batch Size
:return: Preprocessed target data
... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Encoding
Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn(). | def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param keep_prob: Dropout keep probability
:return: RNN state
"""
lstm = tf.contrib.rnn.Basic... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Decoding - Training
Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs. | def decoding_layer_train(encoder_state, dec_cell, dec_embed_input,
sequence_length, decoding_scope, output_fn, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
:param dec_embed_input: Decoder embedded ... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Decoding - Inference
Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder(). | from tensorflow.contrib.seq2seq import simple_decoder_fn_inference, \
dynamic_rnn_decoder
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings,
start_of_sequence_id, end_of_sequence_id,
maximum... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Create RNN cell for decoding using rnn_size and num_layers.
Create the output fuction using lambda to transform it's input, logits, to class logits.
Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_le... | from tensorflow.contrib.rnn import BasicLSTMCell, MultiRNNCell
from tensorflow.contrib.layers import linear
def decoding_layer(dec_embed_input, dec_embeddings, encoder_state,
vocab_size, sequence_length, rnn_size, num_layers,
target_vocab_to_int, keep_prob):
"""
Create de... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Build the Neural Network
Apply the functions you implemented above to:
Apply embedding to the input data for the encoder.
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob).
Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function... | def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length,
source_vocab_size, target_vocab_size, enc_embedding_size,
dec_embedding_size, rnn_size, num_layers, target_vocab_to_int):
"""
Build the Sequence-to-Sequence part of the neural network
:par... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_siz... | # Number of Epochs
epochs = 10
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 200
decoding_embedding_size = 200
# Learning Rate
learning_rate = 0.001
# Dropout Keep Probability
keep_probability = 0.5 | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Build the Graph
Build the graph using the neural network you implemented. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
max_target_sentence_length = max([len(sentence) for sentence in source_int_text])
train_graph = tf.Graph()
with train_graph.as_default():... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Train
Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem. | %pdb off
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import time
def get_accuracy(target, logits):
"""
Calculate accuracy
"""
max_seq = max(target.shape[1], logits.shape[1])
if max_seq - target.shape[1]:
target = np.pad(
target_batch,
[(0,0),(0,max_seq - target_batch.... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id. | def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
sentences = sentence.lower()
words = sentences.split()
unk_id = vocab_to_i... | 4_dlnd_language_translation/dlnd_language_translation.ipynb | NagyAttila/Udacity_DLND_Assigments | gpl-3.0 |
NOTE on notation
* _x, _y, _z, ...: NumPy 0-d or 1-d arrays
* _X, _Y, _Z, ...: NumPy 2-d or higer dimensional arrays
* x, y, z, ...: 0-d or 1-d tensors
* X, Y, Z, ...: 2-d or higher dimensional tensors
Scan
Q1. Compute the cumulative sum of X along the second axis. | _X = np.array([[1,2,3], [4,5,6]])
X = tf.convert_to_tensor(_X)
out = tf.cumsum(X, axis=1)
print(out.eval())
_out = np.cumsum(_X, axis=1)
assert np.array_equal(out.eval(), _out) # tf.cumsum == np.cumsum | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q2. Compute the cumulative product of X along the second axis. | _X = np.array([[1,2,3], [4,5,6]])
X = tf.convert_to_tensor(_X)
out = tf.cumprod(X, axis=1)
print(out.eval())
_out = np.cumprod(_X, axis=1)
assert np.array_equal(out.eval(), _out) # tf.cumprod == np.cumprod | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Segmentation
Q3. Compute the sum along the first two elements and
the last two elements of X separately. | _X = np.array(
[[1,2,3,4],
[-1,-2,-3,-4],
[-10,-20,-30,-40],
[10,20,30,40]])
X = tf.convert_to_tensor(_X)
out = tf.segment_sum(X, [0, 0, 1, 1])
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q4. Compute the product along the first two elements and the last two elements of X separately. | _X = np.array(
[[1,2,3,4],
[1,1/2,1/3,1/4],
[1,2,3,4],
[-1,-1,-1,-1]])
X = tf.convert_to_tensor(_X)
out = tf.segment_prod(X, [0, 0, 1, 1])
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q5. Compute the minimum along the first two elements and the last two elements of X separately. | _X = np.array(
[[1,4,5,7],
[2,3,6,8],
[1,2,3,4],
[-1,-2,-3,-4]])
X = tf.convert_to_tensor(_X)
out = tf.segment_min(X, [0, 0, 1, 1])
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q6. Compute the maximum along the first two elements and the last two elements of X separately. | _X = np.array(
[[1,4,5,7],
[2,3,6,8],
[1,2,3,4],
[-1,-2,-3,-4]])
X = tf.convert_to_tensor(_X)
out = tf.segment_max(X, [0, 0, 1, 1])
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q7. Compute the mean along the first two elements and the last two elements of X separately. | _X = np.array(
[[1,2,3,4],
[5,6,7,8],
[-1,-2,-3,-4],
[-5,-6,-7,-8]])
X = tf.convert_to_tensor(_X)
out = tf.segment_mean(X, [0, 0, 1, 1])
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q8. Compute the sum along the second and fourth and
the first and third elements of X separately in the order. | _X = np.array(
[[1,2,3,4],
[-1,-2,-3,-4],
[-10,-20,-30,-40],
[10,20,30,40]])
X = tf.convert_to_tensor(_X)
out = tf.unsorted_segment_sum(X, [1, 0, 1, 0], 2)
print(out.eval())
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Sequence Comparison and Indexing
Q9. Get the indices of maximum and minimum values of X along the second axis. | _X = np.random.permutation(10).reshape((2, 5))
print("_X =", _X)
X = tf.convert_to_tensor(_X)
out1 = tf.argmax(X, axis=1)
out2 = tf.argmin(X, axis=1)
print(out1.eval())
print(out2.eval())
_out1 = np.argmax(_X, axis=1)
_out2 = np.argmin(_X, axis=1)
assert np.allclose(out1.eval(), _out1)
assert np.allclose(out2.eval(),... | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q10. Find the unique elements of x that are not present in y. | _x = np.array([0, 1, 2, 5, 0])
_y = np.array([0, 1, 4])
x = tf.convert_to_tensor(_x)
y = tf.convert_to_tensor(_y)
out = tf.setdiff1d(x, y)[0]
print(out.eval())
_out = np.setdiff1d(_x, _y)
assert np.array_equal(out.eval(), _out)
# Note that tf.setdiff1d returns a tuple of (out, idx),
# whereas np.setdiff1d returns out... | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q11. Return the elements of X, if X < 4, otherwise X*10. | _X = np.arange(1, 10).reshape(3, 3)
X = tf.convert_to_tensor(_X)
out = tf.where(X < 4, X, X*10)
print(out.eval())
_out = np.where(_X < 4, _X, _X*10)
assert np.array_equal(out.eval(), _out) # tf.where == np.where
| programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q12. Get unique elements and their indices from x. | _x = np.array([1, 2, 6, 4, 2, 3, 2])
x = tf.convert_to_tensor(_x)
out, indices = tf.unique(x)
print(out.eval())
print(indices.eval())
_out, _indices = np.unique(_x, return_inverse=True)
print("sorted unique elements =", _out)
print("indices =", _indices)
# Note that tf.unique keeps the original order, whereas
# np.u... | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Q13. Compute the edit distance between hypothesis and truth. | # Check the documentation on tf.SparseTensor if you are not
# comfortable with sparse tensor.
hypothesis = tf.SparseTensor(
[[0, 0],[0, 1],[0, 2],[0, 4]],
["a", "b", "c", "a"],
(1, 5))
# Note that this is equivalent to the dense tensor.
# [["a", "b", "c", 0, "a"]]
truth = tf.SparseTensor(
[[0, 0],[0, ... | programming/Python/tensorflow/exercises/Math_Part3_Solutions.ipynb | diegocavalca/Studies | cc0-1.0 |
Import the data
pmdarima contains an embedded datasets submodule that allows us to try out models on common datasets. We can load the MSFT stock data from pmdarima 1.3.0+: | from pmdarima.datasets.stocks import load_msft
df = load_msft()
df.head() | examples/stock_market_example.ipynb | alkaline-ml/pmdarima | mit |
Split the data
As in the blog post, we'll use 80% of the samples as training data. Note that a time series' train/test split is different from that of a dataset without temporality; order must be preserved if we hope to discover any notable trends. | train_len = int(df.shape[0] * 0.8)
train_data, test_data = df[:train_len], df[train_len:]
y_train = train_data['Open'].values
y_test = test_data['Open'].values
print(f"{train_len} train samples")
print(f"{df.shape[0] - train_len} test samples") | examples/stock_market_example.ipynb | alkaline-ml/pmdarima | mit |
Pre-modeling analysis
TDS fixed p at 5 based on some lag plot analysis: | from pandas.plotting import lag_plot
fig, axes = plt.subplots(3, 2, figsize=(12, 16))
plt.title('MSFT Autocorrelation plot')
# The axis coordinates for the plots
ax_idcs = [
(0, 0),
(0, 1),
(1, 0),
(1, 1),
(2, 0),
(2, 1)
]
for lag, ax_coords in enumerate(ax_idcs, 1):
ax_row, ax_col = ax_c... | examples/stock_market_example.ipynb | alkaline-ml/pmdarima | mit |
All lags look fairly linear, so it's a good indicator that an auto-regressive model is a good choice. Therefore, we'll allow the auto_arima to select the lag term for us, up to 6.
Estimating the differencing term
We can estimate the best lag term with several statistical tests: | from pmdarima.arima import ndiffs
kpss_diffs = ndiffs(y_train, alpha=0.05, test='kpss', max_d=6)
adf_diffs = ndiffs(y_train, alpha=0.05, test='adf', max_d=6)
n_diffs = max(adf_diffs, kpss_diffs)
print(f"Estimated differencing term: {n_diffs}") | examples/stock_market_example.ipynb | alkaline-ml/pmdarima | mit |
Use auto_arima to fit a model on the data. | auto = pm.auto_arima(y_train, d=n_diffs, seasonal=False, stepwise=True,
suppress_warnings=True, error_action="ignore", max_p=6,
max_order=None, trace=True)
print(auto.order)
from sklearn.metrics import mean_squared_error
from pmdarima.metrics import smape
model = auto
def f... | examples/stock_market_example.ipynb | alkaline-ml/pmdarima | mit |
Date picker | widgets.DatePicker(
description='Pick a Date'
) | docs/source/examples/Widget List.ipynb | cornhundred/ipywidgets | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.