markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The date are integers representing the number of days from an origin date. The origin date for this dataset is determined from here and here and is "1899-12-30". The Period integers refer to 30 minute intervals in a 24 hour day, hence there are 48 for each day.
Let's extract the date and date-time. | df["Date"] = df["Date"].apply(lambda x: pd.Timestamp("1899-12-30") + pd.Timedelta(x, unit="days"))
df["ds"] = df["Date"] + pd.to_timedelta((df["Period"]-1)*30, unit="m") | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
We will be interested in OperationalLessIndustrial which is the electricity demand excluding the demand from certain high energy industrial users. We will resample the data to hourly and filter the data to the same time period as original MSTL paper [1] which is the first 149 days of the year 2012. | timeseries = df[["ds", "OperationalLessIndustrial"]]
timeseries.columns = ["ds", "y"] # Rename to OperationalLessIndustrial to y for simplicity.
# Filter for first 149 days of 2012.
start_date = pd.to_datetime("2012-01-01")
end_date = start_date + pd.Timedelta("149D")
mask = (timeseries["ds"] >= start_date) & (timeser... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Decompose electricity demand using MSTL
Let's apply MSTL to this dataset.
Note: stl_kwargs are set to give results close to [1] which used R and therefore has a slightly different default settings for the underlying STL parameters. It would be rare to manually set inner_iter and outer_iter explicitly in practice. | mstl = MSTL(timeseries["y"], periods=[24, 24 * 7], iterate=3, stl_kwargs={"seasonal_deg": 0,
"inner_iter": 2,
"outer_iter": 0})
res = mstl.fit() # Use .fit() to perform and... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
The multiple seasonal components are stored as a pandas dataframe in the seasonal attribute: | res.seasonal.head() | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Let's inspect the seasonal components in a bit more detail and look at the first few days and weeks to examine the daily and weekly seasonality. | fig, ax = plt.subplots(nrows=2, figsize=[10,10])
res.seasonal["seasonal_24"].iloc[:24*3].plot(ax=ax[0])
ax[0].set_ylabel("seasonal_24")
ax[0].set_title("Daily seasonality")
res.seasonal["seasonal_168"].iloc[:24*7*3].plot(ax=ax[1])
ax[1].set_ylabel("seasonal_168")
ax[1].set_title("Weekly seasonality")
plt.tight_layout... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
We can see that the daily seasonality of electricity demand is well captured. This is the first few days in January so during the summer months in Australia there is a peak in the afternoon most likely due to air conditioning use.
For the weekly seasonality we can see that there is less usage during the weekends.
One ... | fig, ax = plt.subplots(nrows=2, figsize=[10,10])
mask = res.seasonal.index.month==5
res.seasonal[mask]["seasonal_24"].iloc[:24*3].plot(ax=ax[0])
ax[0].set_ylabel("seasonal_24")
ax[0].set_title("Daily seasonality")
res.seasonal[mask]["seasonal_168"].iloc[:24*7*3].plot(ax=ax[1])
ax[1].set_ylabel("seasonal_168")
ax[1].se... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Now we can see an additional peak in the evening! This could be related to heating and lighting now required in the evenings. So this makes sense. We see that main weekly pattern of lower demand over the weekends continue.
The other components can also be extracted from the trend and resid attribute: | display(res.trend.head()) # trend component
display(res.resid.head()) # residual component | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Build a simple keras DNN model
We will use feature columns to connect our raw data to our keras DNN model. Feature columns make it easy to perform common types of feature engineering on your raw data. For example, you can one-hot encode categorical data, create feature crosses, embeddings and more. We'll cover these in... | INPUT_COLS = [
'pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'passenger_count',
]
# Create input layer of feature columns
# TODO 1
feature_columns = # TODO: Your code goes here. | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Next, we create the DNN model. The Sequential model is a linear stack of layers and when building a model using the Sequential API, you configure each layer of the model in turn. Once all the layers have been added, you compile the model.
Lab Task #2a: Create a deep neural network using Keras's Sequential API. In the ... | # Build a keras DNN model using Sequential API
# TODO 2a
model = # TODO: Your code goes here. | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Next, to prepare the model for training, you must configure the learning process. This is done using the compile method. The compile method takes three arguments:
An optimizer. This could be the string identifier of an existing optimizer (such as rmsprop or adagrad), or an instance of the Optimizer class.
A loss funct... | # TODO 2b
# Create a custom evalution metric
def rmse(y_true, y_pred):
return # TODO: Your code goes here
# Compile the keras model
# TODO: Your code goes here. | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
There are various arguments you can set when calling the .fit method. Here x specifies the input data which in our case is a tf.data dataset returning a tuple of (inputs, targets). The steps_per_epoch parameter is used to mark the end of training for a single epoch. Here we are training for NUM_EVALS epochs. Lastly, fo... | # TODO 3
%time
steps_per_epoch = # TODO: Your code goes here.
LOGDIR = "./taxi_trained"
history = # TODO: Your code goes here. | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Export and deploy our model
Of course, making individual predictions is not realistic, because we can't expect client code to have a model object in memory. For others to use our trained model, we'll have to export our model to a file, and expect client code to instantiate the model from that exported file.
We'll expo... | # TODO 4a
OUTPUT_DIR = "./export/savedmodel"
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
EXPORT_PATH = os.path.join(OUTPUT_DIR,
datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
tf.saved_model.save( # TODO: Your code goes here.
# TODO 4b
!saved_model_cli show \
--tag_set # TODO: Your co... | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Deploy our model to AI Platform
Finally, we will deploy our trained model to AI Platform and see how we can make online predicitons.
Lab Task #5a: Complete the code in the cell below to deploy your trained model to AI Platform using the gcloud ai-platform versions create command. Have a look at the documentation for h... | %%bash
# TODO 5a
PROJECT= #TODO: Change this to your PROJECT
BUCKET=${PROJECT}
REGION=us-east1
MODEL_NAME=taxifare
VERSION_NAME=dnn
if [[ $(gcloud ai-platform models list --format='value(name)' | grep $MODEL_NAME) ]]; then
echo "$MODEL_NAME already exists"
else
echo "Creating $MODEL_NAME"
gcloud ai-platf... | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Lab Task #5b: Complete the code in the cell below to call prediction on your deployed model for the example you just created in the input.json file above. | # TODO 5b
!gcloud ai-platform predict \
--model #TODO: Your code goes here.
--json-instances #TODO: Your code goes here.
--version #TODO: Your code goes here. | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/3_keras_sequential_api.ipynb | turbomanage/training-data-analyst | apache-2.0 |
.shape is a tuple of the number of rows and the number of columns: | grades.shape | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
.head() returns the first 5 rows of a DataFrame, .tail() returns the last ones. These are very useful for manual data inspection. You should always check what the contents of your dataframes. | grades.head() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Printing other only the last two elements: | grades.tail(2) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Each of these operations return a new dataframe. We can confirm this via their object identity: | id(grades), id(grades.tail(2)) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
But these objects are not copied unless we explicitly ask for a copy: | grades.tail(2).copy() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting rows, columns and cells
The first boldfaced column of the table is the index column. It's possible to use multiple columns as index (Multiindex).
Selecting columns | grades['teacher'] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The name of the column is also exposed as an attribute as long as it adheres to the naming limitations of attributes (no spaces, starts with a letter, doesn't crash with a method name): | grades.teacher | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The type of a column is pd.Series, which is the type for a vector: | type(grades.teacher)
grades.teacher.shape | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can select multiple columns with a list of column names instead of a column name. Note the double square brackets. | grades[['grade', 'teacher']] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The return type of the operator [] depends on the type of the index. If it's a string, it returns a Series if it's a list, it returns a DataFrame: | print(type(grades[['grade']]))
grades[['grade']] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting rows
Rows can be selected
by their index or
by their integer location.
To demonstrate this, we will use the subject name as the index. Note that it's now in bold: | grades = grades.set_index('subject')
grades | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting by index
Note that you need to use [] not (): | grades.loc['Physics 1i'] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The type of one row is a Series since it's a vector: | type(grades.loc['Physics 1i']) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting by integer location | grades.iloc[2] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can use ranges here as well. Note that the range is upper-bound exclusive, in other words, .iloc[i:j] will not include element j: | grades.iloc[1:3] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting columns with iloc | grades.iloc[:, [0, 2]]
grades.iloc[:, 1:-1]
grades.iloc[1:5, 1:2] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Selecting a cell
There are multiple ways of selecting a single cell, this is perhaps the easiest one: | grades.loc['Physics 1i', 'grade'] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Vectorized operations
Arithmetic operators are overloaded for DataFrames and Series allowing vectorized operations | grades['grade'] + 1
grades[['grade', 'semester']] + 1 | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Comparisions are overloaded as well: | grades['semester'] == 1 | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The index can be manipulated in a similar way but the return value is different: | grades.index == 'System theory' | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
It is generally used to override the index: | old_index = grades.index.copy()
grades.index = grades.index.str.upper()
grades | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Changing it back: | grades.index = old_index
grades | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Vectorized string operations
String columns have a .str namespace with many string operations: | grades['teacher'].str
grades['teacher'].str.contains('Smith') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
It also provides access to the character array: | grades['teacher'].str[:5] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
apply
.apply allows running arbitrary functions on each element of a Series (or a DataFrame): | def get_last_name(name):
return name.split(" ")[1]
grades['teacher'].apply(get_last_name) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The same with a lambda function: | grades['teacher'].apply(lambda name: name.split(" ")[1]) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
apply on rows
apply also works on full dataframes. The parameter is a row (axis=1) or a column in this case. | def format_grade_and_completion(row):
grade = row['grade']
completed = row['completion_date'].strftime("%b %Y")
return f"grade: {grade}, completed: {completed}"
grades.apply(format_grade_and_completion, axis=1) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Vectorized date manipulation
Date columns can be manipulated through the dt namespace: | grades['completion_date'].dt
grades['completion_date'].dt.day_name()
grades['completion_date'].dt.year | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Filtering
Comparisons return a Series of True/False values | grades.semester == 1 | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
which can be used for filtering rows: | grades[grades.semester == 1] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can also use multiple conditions. Note the parentheses: | grades[(grades.semester == 1) & (grades.teacher.str.contains('Smith'))] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Handling multiple dataframes, merge
Let's define a second Dataframe with the credit values of some classes: | credits = pd.DataFrame(
{
'subject': ['Calculus 1', 'Physics 1i', 'Physics 2i'],
'credit': [7, 5, 5]
}
)
credits | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
What are the credit values of the classes we have in the grades table? | d = grades.merge(credits, left_index=True, right_on='subject', how='outer')
d | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Merge
Merge has two operands, a left and a right DataFrame.
Parameters:
1. left_index: merge on the index of the left Dataframe
2. right_on: merge on one or more columns of the right Dataframe. This column is credits in this example.
3. how: inner/outer. Exclude/include all rows even if the key of the merge is unmatche... | grades.merge(credits, left_index=True, right_on='subject', how='inner') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can discard rows with NaN values with dropna. Be careful. It discards all rows with any NaN.
This has the same effect as an inner join: | d = d.dropna()
d | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Finding min/max rows
max and min return the highest and lowest values for each column. The return value is a Series with the column names as indices and the maximum/minimum values as the Series values: | print(type(grades.max()))
grades.max() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The location of the maximum/minimum is often more interesting. idxmax and idxmin return where the maximum is: | # grades.idxmax() # we get an error because of the string and the date column
grades[['grade', 'semester']].idxmax() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
The return value(s) of idxmax can directly be used with loc: | grades.loc[grades[['grade', 'semester']].idxmax()] | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
idxmax works similarly for Series but the return value is a single scalar, the index of the maximum: | grades.grade.idxmax() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
groupby
Groupby allows grouping the rows of the Dataframe along any column(s): | g = credits.groupby('credit')
g.groups | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Or on multiple columns: | grades.groupby(['grade', 'semester']).groups | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Or even on conditions: | grades.groupby(grades['semester'] % 2).groups | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can perform operations on the groups: | grades.groupby('semester').mean()
grades.groupby('semester').std() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
size returns the number of elements in each group: | grades.groupby('semester').size() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
stack and unstack
Grouping on multiple columns and then aggregating results in a multiindex: | grades.groupby(['grade', 'semester']).size().index
grades.groupby(['grade', 'semester']).size() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
unstack moves up the innermost index level to columns: | grades.groupby(['grade', 'semester']).size().unstack() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
stack does the opposite: | credits
credits.stack() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Sorting
We can sort Dataframes by their index: | grades.sort_index() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Or by one or more columns: | grades.sort_values(['grade', 'semester']) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
In ascending order: | grades.sort_index(ascending=False) | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Miscellaneous operations
value_counts
value_counts returns the frequency of values in a column: | grades['semester'].value_counts() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
It can't be used on multiple columns but groupby+size does the same: | grades.groupby(['semester', 'grade']).size() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can also plot the histogram of the values with:
Histogram | grades['semester'].hist() | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Visualization
Pandas is integrated with matplotlib, the main plotting module of Python. | grades.plot(y='grade') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Or as a bar chart: | grades.plot(y='grade', kind='bar') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
We can also specify both axes: | grades.plot(x='semester', y='grade', kind='scatter') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Combining groupby and visualization.
Plotting the grade averages by semester: | grades.groupby('semester').mean().plot(kind='bar') | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Or the number of classes per semester: | grades.groupby('semester').size().plot(kind='pie', title="Classes per semester", ylabel="Classes") | notebooks/Pandas_introduction.ipynb | juditacs/labor | lgpl-3.0 |
Bert Pipeline : PyTorch BERT News Classfication
This notebook shows PyTorch BERT end-to-end news classification example using Kubeflow Pipelines.
An example notebook that demonstrates how to:
Get different tasks needed for the pipeline
Create a Kubeflow pipeline
Include Pytorch KFP components to preprocess, train, vis... | ! pip uninstall -y kfp
! pip install --no-cache-dir kfp
import kfp
import json
import os
from kfp.onprem import use_k8s_secret
from kfp import components
from kfp.components import load_component_from_file, load_component_from_url
from kfp import dsl
from kfp import compiler
kfp.__version__ | samples/contrib/pytorch-samples/Pipeline-Bert.ipynb | kubeflow/pipelines | apache-2.0 |
Enter your gateway and the cookie
Use this extension on chrome to get token
Update values for the ingress gateway and auth session | INGRESS_GATEWAY='http://istio-ingressgateway.istio-system.svc.cluster.local'
AUTH="<enter your token here>"
NAMESPACE="kubeflow-user-example-com"
COOKIE="authservice_session="+AUTH
EXPERIMENT="Default" | samples/contrib/pytorch-samples/Pipeline-Bert.ipynb | kubeflow/pipelines | apache-2.0 |
Set Log bucket and Tensorboard Image | MINIO_ENDPOINT="http://minio-service.kubeflow:9000"
LOG_BUCKET="mlpipeline"
TENSORBOARD_IMAGE="public.ecr.aws/pytorch-samples/tboard:latest"
client = kfp.Client(host=INGRESS_GATEWAY+"/pipeline", cookies=COOKIE)
client.create_experiment(EXPERIMENT)
experiments = client.list_experiments(namespace=NAMESPACE)
my_experime... | samples/contrib/pytorch-samples/Pipeline-Bert.ipynb | kubeflow/pipelines | apache-2.0 |
Set Inference parameters | DEPLOY_NAME="bertserve"
MODEL_NAME="bert"
! python utils/generate_templates.py bert/template_mapping.json
prepare_tensorboard_op = load_component_from_file("yaml/tensorboard_component.yaml")
prep_op = components.load_component_from_file(
"yaml/preprocess_component.yaml"
)
train_op = components.load_component_from... | samples/contrib/pytorch-samples/Pipeline-Bert.ipynb | kubeflow/pipelines | apache-2.0 |
Define pipeline | @dsl.pipeline(name="Training pipeline", description="Sample training job test")
def pytorch_bert( # pylint: disable=too-many-arguments
minio_endpoint=MINIO_ENDPOINT,
log_bucket=LOG_BUCKET,
log_dir=f"tensorboard/logs/{dsl.RUN_ID_PLACEHOLDER}",
mar_path=f"mar/{dsl.RUN_ID_PLACEHOLDER}/model-store",
con... | samples/contrib/pytorch-samples/Pipeline-Bert.ipynb | kubeflow/pipelines | apache-2.0 |
Processing game image
Raw atari images are large, 210x160x3 by default. However, we don't need that level of detail in order to learn them.
We can thus save a lot of time by preprocessing game image, including
* Resizing to a smaller shape
* Converting to grayscale
* Cropping irrelevant image parts | from gym.core import ObservationWrapper
from gym.spaces import Box
from scipy.misc import imresize
class PreprocessAtari(ObservationWrapper):
def __init__(self, env):
"""A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it."""
ObservationWrapper.__init__(self,... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Basic agent setup
Here we define a simple agent that maps game images into policy using simple convolutional neural network. | import theano, lasagne
import theano.tensor as T
from lasagne.layers import *
from agentnet.memory import WindowAugmentation
#observation goes here
observation_layer = InputLayer((None,)+observation_shape,)
#4-tick window over images
prev_wnd = InputLayer((None,4)+observation_shape,name='window from last tick')
new_w... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Network body
Here will need to build a convolutional network that consists of 4 layers:
* 3 convolutional layers with 32 filters, 5x5 window size, 2x2 stride
* Choose any nonlinearity but for softmax
* You may want to increase number of filters for the last layer
* Dense layer on top of all convolutions
* anywhere b... | from lasagne.nonlinearities import rectify,elu,tanh,softmax
#network body
conv0 = Conv2DLayer(wnd_reshape,<...>)
conv1 = <another convolutional layer, growing from conv0>
conv2 = <yet another layer...>
dense = DenseLayer(<what is it's input?>,
nonlinearity=tanh,
name='den... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Network head
You will now need to build output layers.
Since we're building advantage actor-critic algorithm, out network will require two outputs:
* policy, $pi(a|s)$, defining action probabilities
* state value, $V(s)$, defining expected reward from the given state
Both those layers will grow from final dense layer f... | #actor head
logits_layer = DenseLayer(dense,n_actions,nonlinearity=None)
#^^^ separately define pre-softmax policy logits to regularize them later
policy_layer = NonlinearityLayer(logits_layer,softmax)
#critic head
V_layer = DenseLayer(dense,1,nonlinearity=None)
#sample actions proportionally to policy_layer
from ag... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Finally, agent
We declare that this network is and MDP agent with such and such inputs, states and outputs | from agentnet.agent import Agent
#all together
agent = Agent(observation_layers=observation_layer,
policy_estimators=(logits_layer,V_layer),
agent_states={new_wnd:prev_wnd},
action_layers=action_layer)
#Since it's a single lasagne network, one can get it's weights, output, et... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Create and manage a pool of atari sessions to play with
To make training more stable, we shall have an entire batch of game sessions each happening independent of others
Why several parallel agents help training: http://arxiv.org/pdf/1602.01783v1.pdf
Alternative approach: store more sessions: https://www.cs.toronto.ed... | from agentnet.experiments.openai_gym.pool import EnvPool
#number of parallel agents
N_AGENTS = 10
pool = EnvPool(agent,make_env, N_AGENTS) #may need to adjust
%%time
#interact for 7 ticks
_,action_log,reward_log,_,_,_ = pool.interact(10)
print('actions:')
print(action_log[0])
print("rewards")
print(reward_log[0]... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Advantage actor-critic
An agent has a method that produces symbolic environment interaction sessions
Such sessions are in sequences of observations, agent memory, actions, q-values,etc
one has to pre-define maximum session length.
SessionPool also stores rewards, alive indicators, etc.
Code mostly copied from here | #get agent's Qvalues obtained via experience replay
#we don't unroll scan here and propagate automatic updates
#to speed up compilation at a cost of runtime speed
replay = pool.experience_replay
_,_,_,_,(logits_seq,V_seq) = agent.get_sessions(
replay,
session_length=SEQ_LENGTH,
experience_replay=True,
... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Demo run | untrained_reward = np.mean(pool.evaluate(save_path="./records",
record_video=True))
#show video
from IPython.display import HTML
import os
video_names = list(filter(lambda s:s.endswith(".mp4"),os.listdir("./records/")))
HTML("""
<video width="640" height="480" controls>
<so... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Training loop | #starting epoch
epoch_counter = 1
#full game rewards
rewards = {}
loss,reward_per_tick,reward =0,0,0
from tqdm import trange
from IPython.display import clear_output
#the algorithm almost converges by 15k iterations, 50k is for full convergence
for i in trange(150000):
#play
pool.update(SEQ_LENGTH)
... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
Evaluating results
Here we plot learning curves and sample testimonials | import pandas as pd
plt.plot(*zip(*sorted(rewards.items(),key=lambda k:k[0])))
from agentnet.utils.persistence import save
save(action_layer,"kung_fu.pcl")
###LOAD FROM HERE
from agentnet.utils.persistence import load
load(action_layer,"kung_fu.pcl")
rw = pool.evaluate(n_games=20,save_path="./records",record_video=T... | hw12/a2c_kungfu_dmia.ipynb | AndreySheka/dl_ekb | mit |
2 Ejercicio
Dados dos diccionarios d1 y d2, escribe una función en Python llamada fusion que realice la fusión de los dos diccionarios pasados como parámetros. Puedes utilizar la función update.
Prueba la función con los diccionarios d1 = {1: 'A', 2:'B', 3:'C'},
d2 = {4: 'Aa', 5:'Ba', 6:'Ca'}
Utiliza la función l... | # Sol:
def fusion():
d1 = {1: 'A', 2:'B', 3:'C'}
d2 = {4: 'Aa', 5:'Ba', 6:'Ca'}
d1.update(d2)
return d1
fusion() | python/ejercicios/ucm_diccionarios_02_ej.ipynb | xMyrst/BigData | gpl-3.0 |
3 Ejercicio
Dada la lista de las ciudades más pobladas de Italia it:
it = [ 'Roma', 'Milán', 'Nápoles', 'Turín', 'Palermo' , 'Génova',
'Bolonia', 'Florencia', 'Bari', 'Catania']
Crea un diccionario donde la clave sea la posición que ocupa cada ciudad en la lista. Para hacerlo sigue estas indicaciones:
Crea una... | # Sol:
# Definimos la lista con las ciudades que aparece en el enunciado
it = [ 'Roma', 'Milán', 'Nápoles', 'Turín', 'Palermo' , 'Génova', 'Bolonia', 'Florencia', 'Bari', 'Catania', 'Verona']
# Definimos una variable para almacenar una lista que crearemos a partir de un rango [0, longitud de la lista)
# Si no especific... | python/ejercicios/ucm_diccionarios_02_ej.ipynb | xMyrst/BigData | gpl-3.0 |
It looks like GDP has the strongest association with happiness (or satisfaction), followed by social support, life expectancy, and freedom.
After controlling for those other factors, the parameters of the other factors are substantially smaller, and since the CI for generosity includes 0, it is plausible that generosit... | # Solution
n = 250
k_obs = 140
with pm.Model() as model5:
x = pm.Beta('x', alpha=1, beta=1)
k = pm.Binomial('k', n=n, p=x, observed=k_obs)
trace5 = pm.sample(500, **options)
az.plot_posterior(trace5) | soln/chap19.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise: Now let's use PyMC3 to replicate the solution to the Grizzly Bear problem in <<_TheGrizzlyBearProblem>>, which is based on the hypergeometric distribution.
I'll present the problem with slightly different notation, to make it consistent with PyMC3.
Suppose that during the first session, k=23 bears are tagged.... | # Solution
k = 23
n = 19
x = 4
with pm.Model() as model6:
N = pm.DiscreteUniform('N', 50, 500)
y = pm.HyperGeometric('y', N=N, k=k, n=n, observed=x)
trace6 = pm.sample(1000, **options)
az.plot_posterior(trace6) | soln/chap19.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise: In <<_TheWeibullDistribution>> we generated a sample from a Weibull distribution with $\lambda=3$ and $k=0.8$.
Then we used the data to compute a grid approximation of the posterior distribution of those parameters.
Now let's do the same with PyMC3.
For the priors, you can use uniform distributions as we did ... | data = [0.80497283, 2.11577082, 0.43308797, 0.10862644, 5.17334866,
3.25745053, 3.05555883, 2.47401062, 0.05340806, 1.08386395]
# Solution
with pm.Model() as model7:
lam = pm.Uniform('lam', 0.1, 10.1)
k = pm.Uniform('k', 0.1, 5.1)
y = pm.Weibull('y', alpha=k, beta=lam, observed=data)
trace7 = p... | soln/chap19.ipynb | AllenDowney/ThinkBayes2 | mit |
Now estimate the parameters for the treated group. | data = responses['Treated']
# Solution
with pm.Model() as model8:
mu = pm.Uniform('mu', 20, 80)
sigma = pm.Uniform('sigma', 5, 30)
y = pm.Normal('y', mu, sigma, observed=data)
trace8 = pm.sample(500, **options)
# Solution
with model8:
az.plot_posterior(trace8) | soln/chap19.ipynb | AllenDowney/ThinkBayes2 | mit |
In total, 32 bugs have been discovered: | num_seen = k01 + k10 + k11
num_seen
# Solution
with pm.Model() as model9:
p0 = pm.Beta('p0', alpha=1, beta=1)
p1 = pm.Beta('p1', alpha=1, beta=1)
N = pm.DiscreteUniform('N', num_seen, 350)
q0 = 1-p0
q1 = 1-p1
ps = [q0*q1, q0*p1, p0*q1, p0*p1]
k00 = N - num_seen
data = pm.math... | soln/chap19.ipynb | AllenDowney/ThinkBayes2 | mit |
Now we can start to define the actual convolution code. We start by defining an object that represents a single layer of convolution that does the actual convolution operation followed by pooling over the output of that convolution. These layers will be stacked in the final model. | from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
class LeNetConvPoolLayer(object):
def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)):
assert image_shape[1] == filter_shape[1]
self.input = input
# there are "num input feature maps * fi... | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
This next method uses the convolution layer above to make a stack of them and adds a hidden layer followed by a logistic regression classification layer on top. | import time
import fuel
from fuel.streams import DataStream
from fuel.schemes import SequentialScheme
from fuel.transformers import Cast
fuel.config.floatX = theano.config.floatX = 'float32'
def evaluate_lenet5(train, test, valid,
learning_rate=0.1, n_epochs=200,
nkerns=[20, ... | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
This cell runs the model and allows you to play with a few hyperparameters. The ones below take about 1 to 2 minutes to run. | from fuel.datasets import MNIST
train = MNIST(which_sets=('train',), subset=slice(0, 50000))
valid = MNIST(which_sets=('train',), subset=slice(50000, 60000))
test = MNIST(which_sets=('test',))
params, layer0_out, layer1_out = evaluate_lenet5(train, test, valid,
learnin... | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
For most convolution model it can be interesting to show what the trained filters look like. The code below does that from the parameters returned by the training function above. In this model there isn't much of an effect since the filters are 5x5 and we can't see much unfortunately. | %matplotlib inline
import matplotlib.pyplot as plt
from utils import tile_raster_images
filts1 = params[6].get_value()
filts2 = params[4].get_value()
plt.clf()
# Increase the size of the figure
plt.gcf().set_size_inches(15, 10)
# Make a grid for the two layers
gs = plt.GridSpec(1, 2, width_ratios=[1, 25], height_r... | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
What can also be interesting is to draw the outputs of the filters for an example. This works somewhat better for this model. | %matplotlib inline
import matplotlib.pyplot as plt
from utils import tile_raster_images
# Grab some input examples from the test set (we cheat a bit here)
sample = test.get_data(None, slice(0, 50))[0]
# We will print this example amongst the batch
example = 7
plt.gcf()
# Increase the size of the figure
plt.gcf().se... | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
Some things you can try with this model:
- change the non linearity of the convolution to rectifier unit.
- add an extra mlp layer.
If you break the code too much you can get back to the working initial code by loading the lenet.py file with the cell below. (Or just reset the git repo ...) | %load lenet.py | convnets/lenet.ipynb | nouiz/summerschool2015 | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.