markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
A better wayWhen you have just one column of values, unstack does the same easily | pt = per_bear.unstack('bear_type')
pt.columns = pt.columns.droplevel() # Unstack creates a multiindex on columns
pt.head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
UnstackAnd some extra tricks | pt.stack().head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
This looks kind of what we had expected but:* It's a series, not a DataFrame* The levels of the index are "reversed" to before* The main sort is on the date, yet it used to be on the event type Some More Hacks | stack_back = (pt
.stack()
.to_frame('amount') # Turn Series to DF without calling the DF constructor
.swaplevel() # Swaps the levels of the index
.sort_index()
)
stack_back.head()
stack_back.equals(per_bear) | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
GroupBy ```sqlselect min(B), avg(B), geometric_mean(B), min(C), max(C)from ptgroup by A``` | pt | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Old Ways | pt.groupby('Grizzly')['Polar'].agg(['min','mean']).head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
List Aggregates | pt.groupby('Grizzly')[['Polar','Black']].agg(['min','mean',lambda x: x.prod()/len(x),'max']).head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
* Not what we wanted* MultiIndex* Names are not unique* How do you access `` Dict aggregate | pt.groupby('Grizzly').agg({'Polar':['min','mean',lambda x: x.prod()/len(x)],'Black':['min','max']}) | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
With Rename | pt.groupby('Grizzly').Polar.agg({'min_Polar':'min'})
warnings.simplefilter("ignore")
pt.groupby('Grizzly').agg({
'Polar':{'min_Polar':'min','avg_Polar':'mean','geo_Polar':lambda x: x.prod()/len(x)},
'Black':{'min_Black':'min','max_Black':'max'}
})
warnings.simplefilter("default")
| _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Still a MultiIndex Named Aggregations (New in 0.25)This is also the way to go from `1.0.0` as others will be depracated | def geo(x):
return x.prod()/len(x)
pt.groupby('Grizzly').agg(
min_Polar = pd.NamedAgg(column='Polar', aggfunc='min'),
avg_Polar = pd.NamedAgg(column='Polar', aggfunc='mean'),
geo_Polar = pd.NamedAgg('Polar', geo),
# But actually NamedAgg is optional
min_Black = ('Black','min'),
max_Black = ... | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
ClipLet's say, we know from domain knowledge the that an bear walks around a minimum of 3 and maximum of 12 times at each timestamp. We would like to fix that. In a real world example, we many time want to turn negative numbers to zeroes or some truly big numbers to sum known max. The Old WayIterate over columns and... | cl = pt.copy()
lb = 3
ub = 12
# Needed A loop of 3 lines
for col in ['Grizzly','Polar','Black']:
cl['clipped_{}'.format(col)] = cl[col]
cl.loc[cl[col] < lb,'clipped_{}'.format(col)] = lb
cl.loc[cl[col] > ub,'clipped_{}'.format(col)] = ub
my_utils.plot_clipped(cl) # my_utils can be found in the github repo | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
A better way`.clip(lb,ub)` | cl = pt.copy()
cl['Grizzly'] = cl.Grizzly.clip(3,12)
cl = pt.copy()
# Beutiful One Liner
cl[['clipped_Grizzly','clipped_Polar','clipped_Black']] = cl.clip(5,12)
my_utils.plot_clipped(cl) # my_utils can be found in the github repo | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
ReindexNow we have 3 types of bears 17:00 to 23:00. But we were at the the park from 16:00 to 00:00. We've also been told that this park as Panda bears and Cave bears. In the old way we would have this column assignment with a loop, and for the rows we would have maybe create a columns and do some join. A lot of work... | etypes = ['Grizzly','Polar','Black','Panda','Cave'] # New columns
# Define a date range - Pandas will automatically make this into an index
idx = pd.date_range(start='2018-10-09 16:00:00',end='2018-10-09 23:59:00',freq=pt.index.freq,tz='UTC')
type(idx)
pt.reindex(index=idx, columns=etypes, fill_value=0).head(8)
### Let... | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Method Chaining AssignAssign is for creating new columns on the dataframes. This is instead of`df[new_col] = function(df[old_col])`. They are both one lines, but `.assign` doesn't break the flow. | pt.assign(mean_all = pt.mean(axis=1)).head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
With a callableThis is good when we have a filtering phase before. | pt.assign(mean_all = lambda x: x.mean(axis=1)).head() | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
PipeThink R's `%>%`, `.pipe` is a method that accepts a function. `pipe`, by default, assumes the first argument of this function is a dataframe and passes the current dataframe down the pipeline. The function should return a dataframe also, if you want to continue with the chaining. Yet, it can also return any other ... | def add_to_col(df, col='Grizzly', n = 200):
ret = df.copy()
# A dataframe is mutable, if you don't copy it first, this is prone to many errors.
# I always copy when I enter a function, even if I'm sure it shouldn't change anything.
ret[col] = ret[col] + n
return ret
add_to_col(add_to_col(add_to_col(... | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
You can always do this with multiple lines of `df = do_something(df)` but I think this method is more elegant. Beautiful Code Tells a StoryYour code is not just about making the computer do things. It's about telling a story of what you wish to happen. Sometimes other people will want to read you code. Most time, it i... | df = (pd
.read_csv ('./bear_data.csv', index_col=0, parse_dates=['date_'])
.assign (bear_type=lambda df: df.bear_type.map(bears))
.sort_values ('date_')
.set_index ('date_')
.drop (columns='val_updated')
.groupby ('bear_type')
.resample ('15T')
.ap... | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Bonus! Cool methods I've found but did not fit in the talk's flow. [No Time?](You-don't-have-to-memorize-this) | src = df.copy().loc[:,['mean_bears']] | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Percent Change | src.assign(pct = src.pct_change()).head(11) | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Interval IndexHelps creating a "common language" when talking about time series aggregations. | src = df.copy()
ir = pd.interval_range(start=df.index.min(),
end=df.index.max() + df.index.freq,
freq=df.index.freq)
type(ir)
ir
try:
df.loc['2018-10-09 18:37',:] # Datetime Index
except Exception as e:
print (type(e), e)
# Will result error
src.index = ir # Interva... | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Split StringsThe entire concept of strings is different in `1.0.0` | txt = pd.DataFrame({'text':['hello','dean langsam','diving into pandas is better than reinventing it']})
txt
txt.text.str.split()
txt.text.str.split(expand = True) # Expand to make it a dataframe | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Toy Examples with Pandas Testing | import pandas.util.testing as tm
tm.N, tm.K = 15, 10
st = pd.util.testing.makeTimeDataFrame() * 100
st | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Research with Style! | stnan = st.copy()
stnan[np.random.rand(*stnan.shape) < 0.05] = np.nan # Put some nans in it | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Basic | (stnan
.style
.highlight_null('red')
.highlight_max(color='steelblue', axis = 0) # Max each row
.highlight_min(color ='gold', axis = 1) # Min each columns
)
| /Users/deanl/anaconda3/envs/dont/lib/python3.7/site-packages/jinja2/utils.py:485: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
from collections import MutableMapping
/Users/deanl/anaconda3/envs/dont/lib/python3.7/si... | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Gradient | st.clip(0,100).style.background_gradient( cmap='Purples') | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Custom | def custom_style(val):
if val < -100:
return 'background-color:red'
elif val > 100:
return 'background-color:green'
elif abs(val) <20:
return 'background-color:yellow'
else:
return ''
st.style.applymap(custom_style) | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Bars | (st.style
.bar(subset=['A','D'],color='steelblue')
.bar(subset=['J'],color=['indianred','limegreen'], align='mid')
) | _____no_output_____ | MIT | _Nightly.ipynb | DeanLa/dont_reinvent_pandas |
Interacting with ProtoDash In this notebook we'll combine the ProtoDash and the Partial Effects to obtain feature importances on the digits classifications task.ProtoDash was proposed in _Gurumoorthy, Karthik & Dhurandhar, Amit & Cecchi, Guillermo & Aggarwal, Charu. (2019). Efficient Data Representation by Selecting P... | import numpy as np
import pandas as pd
# automatically differentiable implementation of numpy
import jax.numpy as jnp # v0.2.13
import shap #0.34.0
from sklearn.metrics import classification_report
from sklearn import datasets
from sklearn.model_selection import train_test_split
from IPython.display ... | precision recall f1-score support
0 0.54 0.64 0.58 55
1 0.70 0.80 0.75 55
2 0.53 0.44 0.48 52
3 0.29 0.71 0.41 56
4 0.69 0.69 0.69 ... | BSD-3-Clause | examples/interacting_with_protodash.ipynb | gAldeia/itea-python |
We can use the ``ITEA_summarizer`` to inspect the convergence during the evolution. In the cell below, we'll create 3 plots, one for the fitness (classification accuracy), one for the complexity (number of nodes if the IT expression was converted to a symbolic tree) and number of terms (number of IT terms of the soluti... | fig, ax = plt.subplots(3, 1, figsize=(10, 8), sharex=True)
summarizer = ITEA_summarizer(itea=clf).fit(X_train, y_train).plot_convergence(
data=['fitness', 'complexity', 'n_terms'],
ax=ax,
show=False
)
plt.tight_layout()
plt.show()
# features are named pixel_x_y. Lets extract those coordinates and
# paint ... | _____no_output_____ | BSD-3-Clause | examples/interacting_with_protodash.ipynb | gAldeia/itea-python |
6. Bayes Classification This notebook has the code for the charts in Chapter 6 Install BigQuery moduleYou don't need this on AI Platform, but you need this on plain-old JupyterLab | !pip install google-cloud-bigquery
%load_ext google.cloud.bigquery | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Setup | import os
PROJECT = 'data-science-on-gcp-180606' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'data-science-on-gcp' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
os.environ['BUCKET'] = BUCKET | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Exploration using BigQuery | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import google.cloud.bigquery as bigquery
bq = bigquery.Client()
sql = """
SELECT DISTANCE, DEP_DELAY
FROM `flights.tzcorr`
WHERE RAND() < 0.001 AND dep_delay > -20 AND dep_delay < 30 AND distance < 2000
"""
df = bq.query(sql).... | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Set up views in Spark SQL Start a Spark Session if necessary and get a handle to it. | from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Bayes classification using Spark") \
.getOrCreate()
print(spark) | <pyspark.sql.session.SparkSession object at 0x7f6e9c2088d0>
| Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Set up the schema to read in the CSV files on GCS | from pyspark.sql.types import StringType, FloatType, StructType, StructField
header = 'FL_DATE,UNIQUE_CARRIER,AIRLINE_ID,CARRIER,FL_NUM,ORIGIN_AIRPORT_ID,ORIGIN_AIRPORT_SEQ_ID,ORIGIN_CITY_MARKET_ID,ORIGIN,DEST_AIRPORT_ID,DEST_AIRPORT_SEQ_ID,DEST_CITY_MARKET_ID,DEST,CRS_DEP_TIME,DEP_TIME,DEP_DELAY,TAXI_OUT,WHEELS_OFF,W... | StructType(List(StructField(FL_DATE,StringType,true),StructField(UNIQUE_CARRIER,StringType,true),StructField(AIRLINE_ID,StringType,true),StructField(CARRIER,StringType,true),StructField(FL_NUM,StringType,true),StructField(ORIGIN_AIRPORT_ID,StringType,true),StructField(ORIGIN_AIRPORT_SEQ_ID,StringType,true),StructField(... | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Create a table definition (this is done lazily; the files won't be read until we issue a query): | inputs = 'gs://{}/flights/tzcorr/all_flights-00000-*'.format(BUCKET) # 1/30th
#inputs = 'gs://{}/flights/tzcorr/all_flights-*'.format(BUCKET) # FULL
flights = spark.read\
.schema(schema)\
.csv(inputs)
# this view can now be queried ...
flights.createOrReplaceTempView('flights') | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Example query over the view (this will take a while; it's Spark SQL, not BigQuery): | results = spark.sql('SELECT COUNT(*) FROM flights WHERE dep_delay > -20 AND distance < 2000')
results.show() | +--------+
|count(1)|
+--------+
| 8813|
+--------+
| Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Restrict to train days Let's create a CSV file of the training days | sql = """
SELECT *
FROM `flights.trainday`
"""
df = bq.query(sql).to_dataframe()
df.to_csv('trainday.csv', index=False)
!head -3 trainday.csv
%%bash
gsutil cp trainday.csv gs://${BUCKET}/flights/trainday.csv | Copying file://trainday.csv [Content-Type=text/csv]...
/ [1 files][ 6.3 KiB/ 6.3 KiB]
Operation completed over 1 objects/6.3 KiB.
| Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Create dataframe of traindays, but this time because the file has a header, and is a small file, we can have Spark infer the schema | traindays = spark.read \
.option("header", "true") \
.option("inferSchema", "true") \
.csv('gs://{}/flights/trainday.csv'.format(BUCKET))
traindays.createOrReplaceTempView('traindays')
results = spark.sql('SELECT * FROM traindays')
results.head(5)
statement = """
SELECT
f.FL_DATE AS date,
distance,
d... | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Hexbin plot Create a hexbin plot using Spark (repeat of what we did in BigQuery, except that we are now restricting to train days only). | df = flights[(flights['distance'] < 2000) & (flights['dep_delay'] > -20) & (flights['dep_delay'] < 30)]
df.describe().show() | +-------+----------+-----------------+-------------------+
|summary| date| distance| dep_delay|
+-------+----------+-----------------+-------------------+
| count| 8311| 8311| 8311|
| mean| null|748.7310792925039|-1.4972927445554085|
| stddev| null|441.1... | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Sample the dataframe so that it fits into memory (not a problem in development, but will be on full dataset); then plot it. | pdf = df.sample(False, 0.02, 20).toPandas() # to 100,000 rows approx on complete dataset
g = sns.jointplot(pdf['distance'], pdf['dep_delay'], kind="hex", size=10, joint_kws={'gridsize':20}) | _____no_output_____ | Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Quantization Now find the quantiles | distthresh = flights.approxQuantile('distance', list(np.arange(0, 1.0, 0.1)), 0.02)
distthresh
delaythresh = flights.approxQuantile('dep_delay', list(np.arange(0, 1.0, 0.1)), 0.05)
delaythresh
results = spark.sql('SELECT COUNT(*) FROM flights WHERE dep_delay >= 3 AND dep_delay < 8 AND distance >= 447 AND distance < 557... | +--------+
|count(1)|
+--------+
| 62|
+--------+
| Apache-2.0 | quests/data-science-on-gcp-edition1_tf2/06_dataproc/quantization.ipynb | Glairly/introduction_to_tensorflow |
Simple Reinforcement Learning with Tensorflow: Part 0 - Q-TablesIn this iPython notebook we implement a Q-Table algorithm that solves the FrozenLake problem. To learn more, read here: https://medium.com/@awjuliani/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d19526432... | import gym
import numpy as np
import random
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | Q-Table.ipynb | 4SkyNet/DeepRL-Agents |
Load the environment | env = gym.make('FrozenLake-v0') | _____no_output_____ | MIT | Q-Table.ipynb | 4SkyNet/DeepRL-Agents |
Implement Q-Table learning algorithm | #Initialize table with all zeros
Q = np.zeros([env.observation_space.n,env.action_space.n])
# Set learning parameters
lr = .85
y = .99
num_episodes = 2000
#create lists to contain total rewards and steps per episode
#jList = []
rList = []
for i in range(num_episodes):
#Reset environment and get first new observatio... | _____no_output_____ | MIT | Q-Table.ipynb | 4SkyNet/DeepRL-Agents |
Time series analysis (Pandas) Nikolay Koldunovkoldunovn@gmail.com ================ Here I am going to show just some basic [pandas](http://pandas.pydata.org/) stuff for time series analysis, as I think for the Earth Scientists it's the most interesting topic. If you find this small tutorial useful, I encourage you to ... | import pandas as pd
import numpy as np
%matplotlib inline
pd.set_option('max_rows',15) # this limit maximum numbers of rows
np.set_printoptions(precision=3 , suppress= True) # this is just to make the output look better
pd.__version__ | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Loading data Now, when we are done with preparations, let's get some data. Pandas has very good IO capabilities, but we not going to use them in this tutorial in order to keep things simple. For now we open the file simply with numpy loadtxt: | temp = np.loadtxt('../Week03/Ham_3column.txt') | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Every line in the file consist of three elements: year, month, value: | temp[-1] | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
And here is the shape of our array (note that shape of the file might differ in your case, since data updated monthly): | temp.shape | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Time Series We would like to convert this data in to time series, that can be manipulated naturally and easily. First step, that we have to do is to create the range of dates for our time series. From the file it is clear, that record starts at January 1891 and ends at August 2014 (at the time I am writing this, of co... | dates = pd.date_range('1891-01-01', '2014-08-31', freq='D') | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
As you see syntax is quite simple, and this is one of the reasons why I love Pandas so much :) You can check if the range of dates is properly generated: | dates | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Now we are ready to create our first time series. Dates from the *dates* variable will be our index, and `temp` values will be our, hm... values: | ham = pd.Series(temp[:,3]/10., index=dates)
ham | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Now we can plot complete time series: | ham.plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
or its part: | ham['1980':'1990'].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
or even smaller part: | ham['1980-05-02':'1981-03-17'].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Reference to the time periods is done in a very natural way. You, of course, can also get individual values. By number: | ham[120] | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
or by index (date in our case): | ham['1960-01'] | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
And what if we choose only one year? | ham['1960'] | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Isn't that great? :) ExerciseWhat was temperature in Hampurg at your burthsday? One bonus example :) | ham[ham > 0]['1990':'2000'].plot(style='r*')
ham[ham < 0]['1990':'2000'].plot(style='b*') | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Exercise- plot all positive temperatures (red stars) and negative temperatires (blue stars)- limit this plot by 1990-2000 period Data Frame Now let's make live a bit more interesting and get more data. This will be TMIN time series. We use pandas function `read_csv` to parse dates and create Data Frame | hamm = pd.read_csv('Ham_tmin.txt', parse_dates=True, index_col=0, names=['Time','tmin'])
hamm
type(hamm) | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Time period is the same: | hamm.index | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Now we create Data Frame, that will contain both TMAX and TMIN data. It is sort of an Excel table where the first row contain headers for the columns and firs column is an index: | tmp = pd.DataFrame({'TMAX':ham, 'TMIN':hamm.tmin/10})
tmp | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
One can plot the data straight away: | tmp.plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Or have a look at the first several rows: | tmp.head() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
We can reference each column by its name: | tmp['TMIN'] | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
or as method of the Data Frame variable (if name of the variable is a valid python name): | tmp.TMIN | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
We can simply add column to the Data Frame: | tmp['Diff'] = tmp['TMAX'] - tmp['TMIN']
tmp.head() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
ExerciseFind and plot all differences that are larger than 20 | tmp['Diff'][tmp['Diff']>20].plot(style='r*') | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
And delete it: | del tmp['Diff']
tmp.tail() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Slicing will also work: | tmp['1981-03'].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Statistics Back to simple stuff. We can obtain statistical information over elements of the Data Frame. Default is column wise: | tmp.mean()
tmp.max()
tmp.min() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
You can also do it row-wise: | tmp.mean(1) | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Or get everything at once: | tmp.describe() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
By the way getting correlation coefficients for members of the Data Frame is as simple as: | tmp.corr() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
ExerciseFind mean of all temperatures larger than 5 | tmp[tmp>5].mean() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Resampling Pandas provide easy way to resample data to different time frequency. Two main parameters for resampling is time period you resemple to and the method that you use. By default the method is mean. Following example calculates monthly ('M'): | tmp_mm = tmp.resample("M")
tmp_mm['2000':].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
median: | tmp_mm = tmp.resample("M", how='median')
tmp_mm['2000':].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
You can use your methods for resampling, for example np.max (in this case we change resampling frequency to 3 years): | tmp_mm = tmp.resample("3M", how=np.max)
tmp_mm['2000':].plot() | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
You can specify several functions at once as a list: | tmp_mm = tmp.resample("M", how=['mean', np.min, np.max])
tmp_mm['1900':'2020'].plot(subplots=True, figsize=(10,10))
tmp_mm['2000':].plot(figsize=(10,10)) | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
ExerciseDefine function that will find difference between maximum and minimum values of the time series, and resample our `tmp` variable with this function. | def satardays(x):
xmin = x.min()
xmax = x.max()
diff = xmin - xmax
return diff
tmp_mm = tmp.resample("A", how=satardays)
tmp_mm['2000':].plot()
tmp_mm | _____no_output_____ | CC-BY-3.0 | Week05/06 - Time series analysis (Pandas).ipynb | koldunovn/HCU |
Copyright (c) Microsoft Corporation.Licensed under the MIT License. LightGBM: A Highly Efficient Gradient Boosting Decision TreeThis notebook gives an example of how to perform multiple rounds of training and testing of LightGBM models to generate point forecasts of product sales in retail. We will train the LightGBM ... | %load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import sys
import math
import datetime
import warnings
import numpy as np
import pandas as pd
import lightgbm as lgb
from fclib.models.lightgbm import predict
from fclib.evaluation.evaluation_utils import MAPE
from fclib.common.plot import plot_prediction... | System version: 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0]
LightGBM version: 2.3.0
| MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
Parameter SettingsIn what follows, we define global settings related to the model and feature engineering. LightGBM supports both classification models and regression models. In our case, we set the objective function to `mape` which stands for mean-absolute-percentage-error (MAPE) since we will build a regression mod... | # Data directory
DATA_DIR = os.path.join("ojdata")
# Parameters of LightGBM model
params = {
"objective": "mape",
"num_leaves": 124,
"min_data_in_leaf": 340,
"learning_rate": 0.1,
"feature_fraction": 0.65,
"bagging_fraction": 0.87,
"bagging_freq": 19,
"num_rounds": 940,
"early_stopp... | _____no_output_____ | MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
Feature EngineeringNext we create a function to extract a number of features from the data for training the forecasting model. These features include* datetime features including week, week of the month, and month* historical weekly sales of each orange juice in recent weeks* average sales of each orange juice during ... | def create_features(pred_round, train_dir, lags, window_size, used_columns):
"""Create input features for model training and testing.
Args:
pred_round (int): Prediction round (1, 2, ...)
train_dir (str): Path of the training data directory
lags (np.array): Numpy array including a... | _____no_output_____ | MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
Model TrainingWe then perform a multi-round training by fitting a LightGBM model using the training data in each forecast round. After the models are trained, we apply them to generate forecasts for the target weeks. The paradigm of model training and testing is illustrated in the following diagram | # Train and predict for all forecast rounds
pred_all = []
metric_all = []
train_dir = os.path.join(DATA_DIR, "train")
for r in range(1, N_SPLITS + 1):
print("---------- Round " + str(r) + " ----------")
features, train_end_week = create_features(r, train_dir, lags, window_size, used_columns)
train_fea = fea... | ---------- Round 1 ----------
Maximum training week number is 145
Training LightGBM model started.
Training LightGBM model finished.
Prediction results:
store brand week move
0 2 1 147 9404
1 2 1 148 8103
2 2 2 147 6705
3 2 2 148 6120
4 2 3 147 2214... | MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
Model EvaluationTo evaluate the model performance, we compute MAPE of the forecasts from all the forecast rounds below. | # Evaluate prediction accuracy
test_all = []
test_dir = os.path.join(DATA_DIR, "test")
for r in range(1, N_SPLITS + 1):
test_df = pd.read_csv(os.path.join(test_dir, "test_" + str(r) + ".csv"))
test_all.append(test_df)
test_all = pd.concat(test_all, axis=0).reset_index(drop=True)
test_all["actual"] = test_all["l... | MAPE of the predictions is 36.102958386230824
| MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
Result VisualizationFinally, we plot out the forecast results of a few sample store-brand combinations to visually check the forecasts. Note that there could be gaps in the curve of actual sales due to missing sales data. | results = combined[["week", "store", "brand", "prediction"]]
results.rename(columns={"prediction": "move"}, inplace=True)
actual = combined[["week", "store", "brand", "actual"]]
actual.rename(columns={"actual": "move"}, inplace=True)
store_list = combined["store"].unique()
brand_list = combined["brand"].unique()
plot_... | _____no_output_____ | MIT | forecasting/4_lightgbm.ipynb | kawo123/learning-ai |
External Validation of SWAST Forecasting Model Overall results summary.This notebook generates the overall results summary for the MASE, and prediction intervals for LAS, YAS and WAST. | print('******************Summary of External validation results*****************\n\n')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
from os import listdir
from os.path import isfile, join
from scipy.stats import norm, t
sns.set(style="whitegrid")
cwd = os.get... | _____no_output_____ | MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
Point Estimate Results | error_measures = ['smape', 'rmse', 'mase', 'coverage_80', 'coverage_95']
mypath
#start = len('/external_validation/')
start = len(mypath) - 1
for metric in error_measures:
to_read = [filename for filename in result_files if metric in filename]
model_names = ['.' + name[start:name.index('_', start)] for name in ... | _____no_output_____ | MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
Seperate dataframes for prediction intervals | summary_fa = results_mean.filter(
like="coverage_95").filter(like="fbp-arima").filter(like='mean')
summary_fa2 = results_mean.filter(
like="coverage_80").filter(like="fbp-arima").filter(like='mean') | _____no_output_____ | MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
Overall statistics Mean absolute scaled error | alpha = 0.05
#overall MASE
summary_fa = results_mean.filter(
like="mase").filter(like="fbp-arima").filter(like='mean')
mean = summary_fa.to_numpy().flatten().mean()
print(f'\nOverall External Evaluation Statistics for MASE')
#sample std
std = summary_fa.to_numpy().flatten().std(ddof=1)
n = summary_fa.to_numpy()... |
Overall External Evaluation Statistics for MASE
mean: 0.7275 95% CI (0.7193-0.7357)
median: 0.734, IQR 0.084
middle 90%: 0.641 - 0.834
| MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
80% Prediction interval coverage | alpha = 0.05
#overall 80% PI coverage
mean = summary_fa2.to_numpy().flatten().mean()
print(f'\nOverall External Evaluation Statistics for 80% PI coverage')
#sample std
std = summary_fa2.to_numpy().flatten().std(ddof=1)
n = summary_fa2.to_numpy().flatten().shape[0]
#Confidence interval calculation
se = std / np.sqrt... |
Overall External Evaluation Statistics for 80% PI coverage
mean: 0.8332 95% CI (0.8282-0.8381)
median: 0.837, IQR 0.051
middle 90%: 0.773 - 0.878
| MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
95% prediction interval coverage | summary_fa = results_mean.filter(
like="coverage_95").filter(like="fbp-arima").filter(like='mean')
mean = summary_fa.to_numpy().flatten().mean()
print(f'\nOverall External Evaluation Statistics for 95% PI Coverage')
#sample std
std = summary_fa.to_numpy().flatten().std(ddof=1)
n = summary_fa.to_numpy().flatten()... |
Overall External Evaluation Statistics for 95% PI Coverage
mean: 0.9649 95% CI (0.9626-0.9671)
median: 0.970, IQR 0.019
middle 90%: 0.936 - 0.983
| MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
Overall Results Summary Table | #filter for mase - mean results
region_means = results_mean.filter(
like="mase").filter(like='mean').filter(like='fbp-arima').mean().sort_index()
#filter for mase stdev
region_std = results_mean.filter(
like="mase").filter(like='std').filter(like='fbp-arima').mean().sort_index()
#coverage mean
region_95_mean = ... | MASE Coverage 80 Coverage 95
trust region
london North Central 0.76 (0.11) 0.84 (0.06) 0.94 (0.04)
North East 0.74 (0.08) 0.87 (0.06) 0.97 (0.03)
North West 0.7... | MIT | results/04_summary_external_validation.ipynb | TomMonks/swast-benchmarking |
Fact UtilsGenerating facts in the expected format can be tedious. To make it easier to put data into and get data our of Draco, we an API to convert nested data to facts and vice versa. Available functions```{eval-rst}.. automodule:: draco.fact_utils :members:``` Usage Example | from draco import dict_to_facts, answer_set_to_dict, run_clingo
from pprint import pprint
facts = dict_to_facts({
"mark": "bar",
"encoding": [{
"channel": "x",
"field": "condition"
},{
"channel": "y",
"aggregate": "count"
}]
})
facts
# we can run Clingo and convert the mo... | [<clingo.symbol.Symbol object at 0x7f9c68a9a250>, <clingo.symbol.Symbol object at 0x7f9c68a9aca0>, <clingo.symbol.Symbol object at 0x7f9c68a9a580>, <clingo.symbol.Symbol object at 0x7f9c68a9ad00>, <clingo.symbol.Symbol object at 0x7f9c68a9a790>, <clingo.symbol.Symbol object at 0x7f9c68a9abb0>, <clingo.symbol.Symbol obj... | MIT | docs/api/facts.ipynb | ShreyaBM/draco2 |
Bayesian Regression - Inference Algorithms (Part 2) In [Part I](bayesian_regression.ipynb), we looked at how to perform inference on a simple Bayesian linear regression model using SVI. In this tutorial, we'll explore more expressive guides as well as exact inference techniques. We'll use the same dataset as before. | %reset -sf
import logging
import os
import torch
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from torch.distributions import constraints
import pyro
import pyro.distributions as dist
import pyro.optim as optim
pyro.set_rng_seed(1)
assert pyro.__version__.startswith('1... | _____no_output_____ | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
Bayesian Linear RegressionOur goal is once again to predict log GDP per capita of a nation as a function of two features from the dataset - whether the nation is in Africa, and its Terrain Ruggedness Index, but we will explore more expressive guides. Model + GuideWe will write out the model again, similar to that in ... | def model(is_cont_africa, ruggedness, log_gdp):
a = pyro.sample("a", dist.Normal(0., 10.))
b_a = pyro.sample("bA", dist.Normal(0., 1.))
b_r = pyro.sample("bR", dist.Normal(0., 1.))
b_ar = pyro.sample("bAR", dist.Normal(0., 1.))
sigma = pyro.sample("sigma", dist.Uniform(0., 10.))
mean = a + b_a *... | _____no_output_____ | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
SVIAs before, we will use SVI to perform inference. | from pyro.infer import SVI, Trace_ELBO
svi = SVI(model,
guide,
optim.Adam({"lr": .05}),
loss=Trace_ELBO())
is_cont_africa, ruggedness, log_gdp = train[:, 0], train[:, 1], train[:, 2]
pyro.clear_param_store()
num_iters = 5000 if not smoke_test else 2
for i in range(num_iters):
elb... | _____no_output_____ | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
Let us observe the posterior distribution over the different latent variables in the model. | for site, values in summary(svi_samples).items():
print("Site: {}".format(site))
print(values, "\n") | Site: a
mean std 5% 25% 50% 75% 95%
0 9.177024 0.059607 9.07811 9.140463 9.178211 9.217098 9.27152
Site: bA
mean std 5% 25% 50% 75% 95%
0 -1.890622 0.122805 -2.08849 -1.979107 -1.887476 -1.803683 -1.700853
Site: bR
m... | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
HMCIn contrast to using variational inference which gives us an approximate posterior over our latent variables, we can also do exact inference using [Markov Chain Monte Carlo](http://docs.pyro.ai/en/dev/mcmc.html) (MCMC), a class of algorithms that in the limit, allow us to draw unbiased samples from the true posteri... | from pyro.infer import MCMC, NUTS
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_samples=1000, warmup_steps=200)
mcmc.run(is_cont_africa, ruggedness, log_gdp)
hmc_samples = {k: v.detach().cpu().numpy() for k, v in mcmc.get_samples().items()}
for site, values in summary(hmc_samples).items():
print("Site:... | Site: a
mean std 5% 25% 50% 75% 95%
0 9.182098 0.13545 8.958712 9.095588 9.181347 9.277673 9.402615
Site: bA
mean std 5% 25% 50% 75% 95%
0 -1.847651 0.217768 -2.19934 -1.988024 -1.846978 -1.70495 -1.481822
Site: bR
m... | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
Comparing Posterior DistributionsLet us compare the posterior distribution of the latent variables that we obtained from variational inference with those from Hamiltonian Monte Carlo. As can be seen below, for Variational Inference, the marginal distribution of the different regression coefficients is under-dispersed ... | sites = ["a", "bA", "bR", "bAR", "sigma"]
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))
fig.suptitle("Marginal Posterior density - Regression Coefficients", fontsize=16)
for i, ax in enumerate(axs.reshape(-1)):
site = sites[i]
sns.distplot(svi_samples[site], ax=ax, label="SVI (DiagNormal)")
s... | _____no_output_____ | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
MultivariateNormal GuideAs comparison to the previously obtained results from Diagonal Normal guide, we will now use a guide that generates samples from a Cholesky factorization of a multivariate normal distribution. This allows us to capture the correlations between the latent variables via a covariance matrix. If ... | from pyro.infer.autoguide import AutoMultivariateNormal, init_to_mean
guide = AutoMultivariateNormal(model, init_loc_fn=init_to_mean)
svi = SVI(model,
guide,
optim.Adam({"lr": .01}),
loss=Trace_ELBO())
is_cont_africa, ruggedness, log_gdp = train[:, 0], train[:, 1], train[:, 2]
pyro.... | Elbo loss: 703.0100790262222
Elbo loss: 444.6930855512619
Elbo loss: 258.20718491077423
Elbo loss: 249.05364602804184
Elbo loss: 247.2170884013176
Elbo loss: 247.28261297941208
Elbo loss: 246.61236548423767
Elbo loss: 249.86004841327667
Elbo loss: 249.1157277226448
Elbo loss: 249.86634194850922
| MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
Let's look at the shape of the posteriors again. You can see the multivariate guide is able to capture more of the true posterior. | predictive = Predictive(model, guide=guide, num_samples=num_samples)
svi_mvn_samples = {k: v.reshape(num_samples).detach().cpu().numpy()
for k, v in predictive(log_gdp, is_cont_africa, ruggedness).items()
if k != "obs"}
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))
f... | _____no_output_____ | MIT | examples/bayesian_regression_ii.ipynb | fehiepsi/website |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.