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 |
|---|---|---|---|---|---|
Mapping QTL in BXD mice using R/qtl2[Karl Broman](https://kbroman.org)[](https://orcid.org/0000-0002-4914-6671),[Department of Biostatistics & Medical Informatics](https://www.biostat.wisc.edu), [University of Wisconsin–Madison](https://www.wisc.edu)Our aim in this tutorial is to demonstrate how to map quantitat... | install.packages("GNapi", repos="http://rqtl.org/qtl2cran")
library(GNapi) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
The [R/GNapi](https://github.com/kbroman/GNapi) has a variety of functions. For an overview, see [its vignette](http://kbroman.org/GNapi/GNapi.html). Here we will just do one thing: use the function `get_pheno()` to grab BXD phenotype data. You provide a data set and a phenotype. Phenotype 10038 concerns "habituation",... | phe <- get_pheno("BXD", "10038")
head(phe) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
We will use just the column "value", but we need to include the strain names so that R/qtl2 can line up these phenotypes with the genotypes. | pheno <- setNames(phe$value, phe$sample_name)
head(pheno) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
Acquire genotype data with R/qtl2We now want to get genotype data for the BXD panel. We first need to install the [R/qtl2](https://kbroman.org/qtl2) package. As with R/GNapi, it is not available on CRAN, but rather is distributed via a private repository.```rinstall.packages("qtl2", repos="http://rqtl.org/qtl2cran")``... | install.packages("qtl2", repos="http://rqtl.org/qtl2cran")
library(qtl2) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
R/qtl2 uses a special file format for QTL data ([described here](https://kbroman.org/qtl2/assets/vignettes/input_files.html)). There are a variety of sample datasets [on Github](https://github.com/rqtl/qtl2data), including genotypes for the [mouse BXD lines](https://github.com/rqtl/qtl2data/tree/master/BXD), taken from... | bxd_file <- "https://raw.githubusercontent.com/rqtl/qtl2data/master/BXD/bxd.zip"
bxd <- read_cross2(bxd_file) | Warning message in recode_geno(sheet, genotypes):
โ117497 genotypes treated as missing: "H"โ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
We get a warning message about heterozygous genotypes being omitted. A number of the newer BXD lines have considerable heterozygosity. But these lines weren't among those phenotyped in the data we downloaded above, and so we don't need to worry about it here.The data are read into the object `bxd`, which has class `"cr... | print( summary(bxd) ) | Object of class cross2 (crosstype "risib")
Total individuals 198
No. genotyped individuals 198
No. phenotyped individuals 198
No. with both geno & pheno 198
No. phenotypes 5806
No. covariates 0
No. phenotype covariates 1
No. chromosomes 20
To... | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
The first step in QTL analysis is to calculate genotype probabilities at putative QTL positions across the genome, conditional on the observed marker data. This allows us that consider positions between the genotyped markers and to allow for the presence of genotyping errors.First, we need to define the positions that ... | gmap <- insert_pseudomarkers(bxd$gmap, step=0.2, stepwidth="max") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
We will be interested in results with respect to the physical map (in Mbp), and so we need to create a corresponding map that includes the pseudomarker positions. We do this with the function `interp_map()`, which uses linear interpolation to get estimated positions for the inserted pseudomarkers. | pmap <- interp_map(gmap, bxd$gmap, bxd$pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
We can now proceed with calculating genotype probabilities for all BXD strains at all markers and pseudomarkers, conditional on the observed marker genotypes and assuming a 0.2% genotyping error rate. We use the [Carter-Falconer](https://doi.org/10.1007/BF02996226) map function to convert between cM and recombination f... | pr <- calc_genoprob(bxd, gmap, error_prob=0.002, map_function="c-f") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
In the QTL analysis, we will fit a linear mixed model to account for polygenic background effects. We will use the "leave one chromosome out" (LOCO) method for this. When we scan a chromosome for a QTL, we include a polygenic term with a kinship matrix derived from all other chromosomes. We first need to calculate this... | k <- calc_kinship(pr, "loco") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
Now, finally, we're ready to perform the genome scan, which we do with the function `scan1()`. It takes the genotype probabilities and a set of phenotypes (here, just one phenotype). If kinship matrices are provided (here, as `k`), the scan is performed using a linear mixed model. To make the calculations faster, the r... | out <- scan1(pr, pheno, k) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
The output of `scan1()` is a matrix of LOD scores; the rows are marker/pseudomarker positions and the columns are phenotypes. We can plot the results using `plot.scan1()`, and we can just use `plot()` because it uses the class of its input to determine what plot to make.Here I'm using the package [repr](https://cran.r-... | library(repr)
options(repr.plot.height=4, repr.plot.width=8)
par(mar=c(5.1, 4.1, 0.6, 0.6))
plot(out, pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
There's a clear QTL on chromosome 8. We can make a plot of just that chromosome with the argument `chr=15`. | plot(out, pmap, chr=15) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
Let's create a plot of the phenotype vs the genotype at the inferred QTL. We first need to identify the QTL location, which we can do using `max()`. We then use `maxmarg()` to get inferred genotypes at the inferred QTL. | mx <- max(out, pmap)
g_imp <- maxmarg(pr, pmap, chr=mx$chr, pos=mx$pos, return_char=TRUE) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
We can use `plot_pxg()` to plot the phenotype as a function of QTL genotype. We use `swap_axes=TRUE` to have the phenotype on the x-axis and the genotype on the y-axis, rather than the other way around. Here we see that the BB and DD genotypes are completely separated, phenotypically. | par(mar=c(5.1, 4.1, 0.6, 0.6))
plot_pxg(g_imp, pheno, swap_axes=TRUE, xlab="Habituation phenotype") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
Browse genome scan results with Genetics Genome BrowserThe [Genetics Genome Browser](https://github.com/chfi/purescript-genome-browser) is a fast, lightweight, [purescript]-based genome browser developed for browsing GWAS or QTL analysis results. We'll use the R package [R/qtl2browse](https://github.com/rqtl/qtl2brows... | library(qtl2browse)
browse(out, pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | genenetwork/Teaching_CTC2019 |
Structured and time series data This notebook contains an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn's [Entity Embeddings of Categorical Variables](https://arxiv.org/abs/1604.06737).The motivation behind exploring this architecture is it's relevance to real-w... | %matplotlib inline
%reload_ext autoreload
%autoreload 2
from fastai.structured import *
from fastai.column_data import *
np.set_printoptions(threshold=50, edgeitems=20)
PATH='data/rossmann/' | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Create datasets In addition to the provided data, we will be using external datasets put together by participants in the Kaggle competition. You can download all of them [here](http://files.fast.ai/part2/lesson14/rossmann.tgz).For completeness, the implementation used to put them together is included below. | def concat_csvs(dirname):
path = f'{PATH}{dirname}'
filenames=glob(f"{PATH}/*.csv")
wrote_header = False
with open(f"{path}.csv","w") as outputfile:
for filename in filenames:
name = filename.split(".")[0]
with open(filename) as f:
line = f.readline()
... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Feature Space:* train: Training set provided by competition* store: List of stores* store_states: mapping of store to the German state they are in* List of German state names* googletrend: trend of certain google keywords over time, found by users to correlate well w/ given data* weather: weather* test: testing set | table_names = ['train', 'store', 'store_states', 'state_names',
'googletrend', 'weather', 'test'] | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We'll be using the popular data manipulation framework `pandas`. Among other things, pandas allows you to manipulate tables/data frames in python as one would in a database.We're going to go ahead and load all of our csv's as dataframes into the list `tables`. | tables = [pd.read_csv(f'{PATH}{fname}.csv', low_memory=False) for fname in table_names]
from IPython.display import HTML, display | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We can use `head()` to get a quick look at the contents of each table:* train: Contains store information on a daily basis, tracks things like sales, customers, whether that day was a holdiay, etc.* store: general info about the store including competition, etc.* store_states: maps store to state it is in* state_names:... | for t in tables: display(t.head()) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
This is very representative of a typical industry dataset.The following returns summarized aggregate information to each table accross each field. | for t in tables: display(DataFrameSummary(t).summary()) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Data Cleaning / Feature Engineering As a structured data problem, we necessarily have to go through all the cleaning and feature engineering, even though we're using a neural network. | train, store, store_states, state_names, googletrend, weather, test = tables
len(train),len(test) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We turn state Holidays to booleans, to make them more convenient for modeling. We can do calculations on pandas fields using notation very similar (often identical) to numpy. | train.StateHoliday = train.StateHoliday!='0'
test.StateHoliday = test.StateHoliday!='0' | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
`join_df` is a function for joining tables on specific fields. By default, we'll be doing a left outer join of `right` on the `left` argument using the given fields for each table.Pandas does joins using the `merge` method. The `suffixes` argument describes the naming convention for duplicate fields. We've elected to l... | def join_df(left, right, left_on, right_on=None, suffix='_y'):
if right_on is None: right_on = left_on
return left.merge(right, how='left', left_on=left_on, right_on=right_on,
suffixes=("", suffix)) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Join weather/state names. | weather = join_df(weather, state_names, "file", "StateName") | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
In pandas you can add new columns to a dataframe by simply defining it. We'll do this for googletrends by extracting dates and state names from the given data and adding those columns.We're also going to replace all instances of state name 'NI' to match the usage in the rest of the data: 'HB,NI'. This is a good opportu... | googletrend['Date'] = googletrend.week.str.split(' - ', expand=True)[0]
googletrend['State'] = googletrend.file.str.split('_', expand=True)[2]
googletrend.loc[googletrend.State=='NI', "State"] = 'HB,NI' | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
The following extracts particular date fields from a complete datetime for the purpose of constructing categoricals.You should *always* consider this feature extraction step when working with date-time. Without expanding your date-time into these additional fields, you can't capture any trend/cyclical behavior as a fun... | add_datepart(weather, "Date", drop=False)
add_datepart(googletrend, "Date", drop=False)
add_datepart(train, "Date", drop=False)
add_datepart(test, "Date", drop=False) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
The Google trends data has a special category for the whole of the Germany - we'll pull that out so we can use it explicitly. | trend_de = googletrend[googletrend.file == 'Rossmann_DE'] | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Now we can outer join all of our data into a single dataframe. Recall that in outer joins everytime a value in the joining field on the left table does not have a corresponding value on the right table, the corresponding row in the new table has Null values for all right table fields. One way to check that all records ... | store = join_df(store, store_states, "Store")
len(store[store.State.isnull()])
joined = join_df(train, store, "Store")
joined_test = join_df(test, store, "Store")
len(joined[joined.StoreType.isnull()]),len(joined_test[joined_test.StoreType.isnull()])
joined = join_df(joined, googletrend, ["State","Year", "Week"])
joine... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Next we'll fill in missing values to avoid complications with `NA`'s. `NA` (not available) is how Pandas indicates missing values; many models have problems when missing values are present, so it's always important to think about how to deal with them. In these cases, we are picking an arbitrary *signal value* that doe... | for df in (joined,joined_test):
df['CompetitionOpenSinceYear'] = df.CompetitionOpenSinceYear.fillna(1900).astype(np.int32)
df['CompetitionOpenSinceMonth'] = df.CompetitionOpenSinceMonth.fillna(1).astype(np.int32)
df['Promo2SinceYear'] = df.Promo2SinceYear.fillna(1900).astype(np.int32)
df['Promo2SinceWee... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Next we'll extract features "CompetitionOpenSince" and "CompetitionDaysOpen". Note the use of `apply()` in mapping a function across dataframe values. | for df in (joined,joined_test):
df["CompetitionOpenSince"] = pd.to_datetime(dict(year=df.CompetitionOpenSinceYear,
month=df.CompetitionOpenSinceMonth, day=15))
df["CompetitionDaysOpen"] = df.Date.subtract(df.CompetitionOpenSince).dt.days | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We'll replace some erroneous / outlying data. | for df in (joined,joined_test):
df.loc[df.CompetitionDaysOpen<0, "CompetitionDaysOpen"] = 0
df.loc[df.CompetitionOpenSinceYear<1990, "CompetitionDaysOpen"] = 0 | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We add "CompetitionMonthsOpen" field, limiting the maximum to 2 years to limit number of unique categories. | for df in (joined,joined_test):
df["CompetitionMonthsOpen"] = df["CompetitionDaysOpen"]//30
df.loc[df.CompetitionMonthsOpen>24, "CompetitionMonthsOpen"] = 24
joined.CompetitionMonthsOpen.unique() | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Same process for Promo dates. | for df in (joined,joined_test):
df["Promo2Since"] = pd.to_datetime(df.apply(lambda x: Week(
x.Promo2SinceYear, x.Promo2SinceWeek).monday(), axis=1).astype(pd.datetime))
df["Promo2Days"] = df.Date.subtract(df["Promo2Since"]).dt.days
for df in (joined,joined_test):
df.loc[df.Promo2Days<0, "Promo2Days"... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Durations It is common when working with time series data to extract data that explains relationships across rows as opposed to columns, e.g.:* Running averages* Time until next event* Time since last eventThis is often difficult to do with most table manipulation frameworks, since they are designed to work with relat... | def get_elapsed(fld, pre):
day1 = np.timedelta64(1, 'D')
last_date = np.datetime64()
last_store = 0
res = []
for s,v,d in zip(df.Store.values,df[fld].values, df.Date.values):
if s != last_store:
last_date = np.datetime64()
last_store = s
if v: last_date = d
... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We'll be applying this to a subset of columns: | columns = ["Date", "Store", "Promo", "StateHoliday", "SchoolHoliday"]
df = train[columns]
df = test[columns] | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Let's walk through an example.Say we're looking at School Holiday. We'll first sort by Store, then Date, and then call `add_elapsed('SchoolHoliday', 'After')`:This will apply to each row with School Holiday:* A applied to every row of the dataframe in order of store and date* Will add to the dataframe the days since se... | fld = 'SchoolHoliday'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
get_elapsed(fld, 'Before') | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We'll do this for two more fields. | fld = 'StateHoliday'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
get_elapsed(fld, 'Before')
fld = 'Promo'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We're going to set the active index to Date. | df = df.set_index("Date") | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Then set null values from elapsed field calculations to 0. | columns = ['SchoolHoliday', 'StateHoliday', 'Promo']
for o in ['Before', 'After']:
for p in columns:
a = o+p
df[a] = df[a].fillna(0).astype(int) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Next we'll demonstrate window functions in pandas to calculate rolling quantities.Here we're sorting by date (`sort_index()`) and counting the number of events of interest (`sum()`) defined in `columns` in the following week (`rolling()`), grouped by Store (`groupby()`). We do the same in the opposite direction. | bwd = df[['Store']+columns].sort_index().groupby("Store").rolling(7, min_periods=1).sum()
fwd = df[['Store']+columns].sort_index(ascending=False
).groupby("Store").rolling(7, min_periods=1).sum() | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Next we want to drop the Store indices grouped together in the window function.Often in pandas, there is an option to do this in place. This is time and memory efficient when working with large datasets. | bwd.drop('Store',1,inplace=True)
bwd.reset_index(inplace=True)
fwd.drop('Store',1,inplace=True)
fwd.reset_index(inplace=True)
df.reset_index(inplace=True) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Now we'll merge these values onto the df. | df = df.merge(bwd, 'left', ['Date', 'Store'], suffixes=['', '_bw'])
df = df.merge(fwd, 'left', ['Date', 'Store'], suffixes=['', '_fw'])
df.drop(columns,1,inplace=True)
df.head() | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
It's usually a good idea to back up large tables of extracted / wrangled features before you join them onto another one, that way you can go back to it easily if you need to make changes to it. | df.to_feather(f'{PATH}df')
df = pd.read_feather(f'{PATH}df')
df["Date"] = pd.to_datetime(df.Date)
df.columns
joined = join_df(joined, df, ['Store', 'Date'])
joined_test = join_df(joined_test, df, ['Store', 'Date']) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
The authors also removed all instances where the store had zero sale / was closed. We speculate that this may have cost them a higher standing in the competition. One reason this may be the case is that a little exploratory data analysis reveals that there are often periods where stores are closed, typically for refurb... | joined = joined[joined.Sales!=0] | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We'll back this up as well. | joined.reset_index(inplace=True)
joined_test.reset_index(inplace=True)
joined.to_feather(f'{PATH}joined')
joined_test.to_feather(f'{PATH}joined_test') | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We now have our final set of engineered features.While these steps were explicitly outlined in the paper, these are all fairly typical feature engineering steps for dealing with time series data and are practical in any similar setting. Create features | joined = pd.read_feather(f'{PATH}joined')
joined_test = pd.read_feather(f'{PATH}joined_test')
joined.head().T.head(40) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Now that we've engineered all our features, we need to convert to input compatible with a neural network.This includes converting categorical variables into contiguous integers or one-hot encodings, normalizing continuous features to standard normal, etc... | cat_vars = ['Store', 'DayOfWeek', 'Year', 'Month', 'Day', 'StateHoliday', 'CompetitionMonthsOpen',
'Promo2Weeks', 'StoreType', 'Assortment', 'PromoInterval', 'CompetitionOpenSinceYear', 'Promo2SinceYear',
'State', 'Week', 'Events', 'Promo_fw', 'Promo_bw', 'StateHoliday_fw', 'StateHoliday_bw',
'SchoolHoliday... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We're going to run on a sample. | idxs = get_cv_idxs(n, val_pct=150000/n)
joined_samp = joined.iloc[idxs].set_index("Date")
samp_size = len(joined_samp); samp_size | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
To run on the full dataset, use this instead: | samp_size = n
joined_samp = joined.set_index("Date") | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We can now process our data... | joined_samp.head(2)
df, y, nas, mapper = proc_df(joined_samp, 'Sales', do_scale=True)
yl = np.log(y)
joined_test = joined_test.set_index("Date")
df_test, _, nas, mapper = proc_df(joined_test, 'Sales', do_scale=True, skip_flds=['Id'],
mapper=mapper, na_dict=nas)
df.head(2) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
In time series data, cross-validation is not random. Instead, our holdout data is generally the most recent data, as it would be in real application. This issue is discussed in detail in [this post](http://www.fast.ai/2017/11/13/validation-sets/) on our web site.One approach is to take the last 25% of rows (sorted by d... | train_ratio = 0.75
# train_ratio = 0.9
train_size = int(samp_size * train_ratio); train_size
val_idx = list(range(train_size, len(df))) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
An even better option for picking a validation set is using the exact same length of time period as the test set uses - this is implemented here: | val_idx = np.flatnonzero(
(df.index<=datetime.datetime(2014,9,17)) & (df.index>=datetime.datetime(2014,8,1)))
val_idx=[0] | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
DL We're ready to put together our models.Root-mean-squared percent error is the metric Kaggle used for this competition. | def inv_y(a): return np.exp(a)
def exp_rmspe(y_pred, targ):
targ = inv_y(targ)
pct_var = (targ - inv_y(y_pred))/targ
return math.sqrt((pct_var**2).mean())
max_log_y = np.max(yl)
y_range = (0, max_log_y*1.2) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We can create a ModelData object directly from out data frame. | md = ColumnarModelData.from_data_frame(PATH, val_idx, df, yl.astype(np.float32), cat_flds=cat_vars, bs=128,
test_df=df_test) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Some categorical variables have a lot more levels than others. Store, in particular, has over a thousand! | cat_sz = [(c, len(joined_samp[c].cat.categories)+1) for c in cat_vars]
cat_sz | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
We use the *cardinality* of each variable (that is, its number of unique values) to decide how large to make its *embeddings*. Each level will be associated with a vector with length defined as below. | emb_szs = [(c, min(50, (c+1)//2)) for _,c in cat_sz]
emb_szs
m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars),
0.04, 1, [1000,500], [0.001,0.01], y_range=y_range)
lr = 1e-3
m.lr_find()
m.sched.plot(100) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Sample | m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars),
0.04, 1, [1000,500], [0.001,0.01], y_range=y_range)
lr = 1e-3
m.fit(lr, 3, metrics=[exp_rmspe])
m.fit(lr, 5, metrics=[exp_rmspe], cycle_len=1)
m.fit(lr, 2, metrics=[exp_rmspe], cycle_len=4) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
All | m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars),
0.04, 1, [1000,500], [0.001,0.01], y_range=y_range)
lr = 1e-3
m.fit(lr, 1, metrics=[exp_rmspe])
m.fit(lr, 3, metrics=[exp_rmspe])
m.fit(lr, 3, metrics=[exp_rmspe], cycle_len=1) | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Test | m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars),
0.04, 1, [1000,500], [0.001,0.01], y_range=y_range)
lr = 1e-3
m.fit(lr, 3, metrics=[exp_rmspe])
m.fit(lr, 3, metrics=[exp_rmspe], cycle_len=1)
m.save('val0')
m.load('val0')
x,y=m.predict_with_targs()
exp_rmspe(x,y)
pred_test=m.predict(True)
p... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
RF | from sklearn.ensemble import RandomForestRegressor
((val,trn), (y_val,y_trn)) = split_by_idx(val_idx, df.values, yl)
m = RandomForestRegressor(n_estimators=40, max_features=0.99, min_samples_leaf=2,
n_jobs=-1, oob_score=True)
m.fit(trn, y_trn);
preds = m.predict(val)
m.score(trn, y_trn), m.sco... | _____no_output_____ | Apache-2.0 | courses/dl1/lesson3-rossman.ipynb | linbojin/fastai |
Dataset Marlon Soybean, CBOT Soybean Futures + ( Global Historical Climatology Network (GHCN) filtered by USDA-NASS-soybeans-production_bushels-2015) Soybean, CBOT Soybean Futures- https://blog.quandl.com/api-for-commodity-data- http://www.quandl.com/api/v3/datasets/CHRIS/CME_S1/ Global Historical Climatology Network... | %matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
import numpy as np
import os
from six.moves import urllib
from ftplib import FTP
from io import StringIO
from IPython.display import clear_output
from functools import reduce
import tarfile
import subprocess
#subp... | Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
| Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Defines | ROOT_PATH = "drive/My Drive/TCC/"
DATASETS_PATH = ROOT_PATH + "datasets/"
SOYBEAN_PATH = DATASETS_PATH + "CBOTSoybeanFutures/"
WEATHER_PATH = DATASETS_PATH + "GHCN_Data/"
SOYBEAN_URL = "http://www.quandl.com/api/v3/datasets/CHRIS/CME_S1/data.csv"
USDA_PATH = "datasets/USDA-NASS-soybeans-production_bushels-2... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
ERROR: type should be string, got " https://github.com/aaronpenne/get_noaa_ghcn_data.git https://github.com/aaronpenne/get_noaa_ghcn_data/blob/master/get_station_id.py" | # -*- coding: utf-8 -*-
"""
Searches list of stations via user input to find the station ID.
Author: Aaron Penne
------------------------------
Variable Columns Type
------------------------------
ID 1-11 Character
LATITUDE 13-20 Real
LONGITUDE 22-30 Real
ELEVATION 32-37 Real
STATE ... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
https://github.com/aaronpenne/get_noaa_ghcn_data/blob/master/get_dly.py |
"""
Grabs .dly file from the NOAA GHCN FTP server, parses, and reshapes to have one
day per row and element values in the columns. Writes output as CSV.
Author: Aaron Penne
.dly Format In (roughly): .csv Format Out (roughly):
------------------------- --------------------------
... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Fetch Data | def fetch_soybean_data(soybean_url=SOYBEAN_URL, soybean_path=SOYBEAN_PATH):
if not os.path.isdir(soybean_path):
os.makedirs(soybean_path)
csv_path = os.path.join(soybean_path, "soybeans.csv")
urllib.request.urlretrieve(soybean_url, csv_path)
def fetch_weather_data(contains='US', weather_path=WEATHE... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Check the number of downloaded station's csv file | weather = get_station(search_term='US') # List all stations from USA
print("# of stations in GHCN FTP: ", end="")
print(str(weather['STATION_ID'].size))
print("# of downloaded csv files: ", end="")
!find "$WEATHER_PATH_DRIVE_CSV" -type f | wc -l
print("# of downloaded stations in control file: ", end="")
with op... | ................................................................................................................................................................................................................................................................................................................................... | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Get 'US' Stations | newfile = ''
with open(PROJECT_PATH+'ghcnd-stations-us.txt', 'r') as f:
for line in f.readlines():
line_list = line.split(' ')
station = line_list[0]
newfile += station
for word in line_list:
if (len(word) > 1):
if (word[0].isalpha() and word!=station):
state = w... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Organize Stations by State | def organize_stations_by_state():
f1='' #stations_not_dowloaded
csv_path = WEATHER_PATH_DRIVE_CSV
with open(WEATHER_PATH+'ghcnd-stations-us.csv', 'r') as f:
for line in f:
station = line.split(',')[0]
state = line.split(',')[1].rstrip()
# Create target Directory if don't exist
if not o... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Fix columns | def fix_columns(df):
for column in df:
if column in ('ID','TMAX','TMIN','TAVG','PRCP'):
pass
else:
#print(' deleting ',column, end='')
del(df[column])
if 'TMAX' not in df:
#print(' creating TMAX... ', end='')
#sLength = sizes['TMAX']
df['TMAX'] = pd.Series(0, index=df.index)
... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Load Data | def load_soybean_data(soybean_path=SOYBEAN_PATH):
csv_path = os.path.join(soybean_path, "soybeans.csv")
print(csv_path)
return pd.read_csv(csv_path)
def load_single_csv(csv_path):
#print(csv_path)
df = pd.read_csv(csv_path,low_memory=False)
df.set_index(['MM/DD/YYYY','YEAR','MONTH','DAY'], inplace=Tr... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Calculate Mean and Standard Deviation for each state | def save_csv(df,name,path):
#print('Saving DataFrame in ',path)
# Create target Directory if don't exist
if not os.path.exists(path):
os.mkdir(path)
print("Directory " , path , " Created ")
df.to_csv(path+name)
def read_log(file_path):
files_processed = ""
if not os.path.exists(file_path):
... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Make the Date column as index | soybeans.Date = pd.to_datetime(soybeans.Date)
soybeans.set_index('Date', inplace=True)
soybeans.head()
soybeans.tail()
plt.plot(soybeans.index, soybeans.Settle)
plt.title('CBOT Soybean Futures',fontsize=27)
plt.ylabel('Price (0.01 $USD)',fontsize=27)
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d')... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Filter soybeans by the year 2015: | mask = (soybeans['Date'] > '2015-01-01') & (soybeans['Date'] <= '2015-12-31')
soybeans = soybeans.loc[mask]
mask = (soybeans['Date'] > '2014-01-01')
soybeans = soybeans.loc[mask] | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Filter weather by the most productive states | weather = weather.query("state in ('IA','IL','MN','NE','IN','OH','SD','ND','MO','AR','KS','MS','MI','WI','KY','TN','LA','NC','PA','VA','MD','AL','GA','NY','OK','SC','DE','NJ','TX','WV','FL')") | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Plot map data | stations = pd.read_csv('US_stations.csv')
#stations.set_index(['LATITUDE','LONGITUDE'], inplace=True)
stations.index.names
#stations.drop_duplicates(subset=['LATITUDE','LONGITUDE'])
stations.plot(kind="scatter", x="LONGITUDE", y="LATITUDE",fontsize=27,figsize=(20,15))
plt.title("Meteorological stations in the USA's mos... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Group data by date (daily)Mรฉdia das medidas horรกrias para o avgtemp, mintemp e maxtemp | weather = weather.groupby(['date'], as_index=False)['date','mintemp','maxtemp','avgtemp'].mean()
weather.head()
weather.date = pd.to_datetime(weather.date)
weather.set_index('date', inplace=True) | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Join datasets (soybeans + weather) | dtMarlon = soybeans.join(weather)
dtMarlon.head() | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Histograms | soybeans.hist(bins=50, figsize=(20,15))
plt.show()
weather.hist(bins=50, figsize=(20,15))
plt.show()
dtMarlon.hist(bins=50, figsize=(20,15))
plt.show() | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Time Series | plt.plot(soybeans.index, soybeans.Settle)
plt.title('CBOT Soybean Futures',fontsize=27)
plt.ylabel('Price (0.01 $USD)',fontsize=27)
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d'))
plt.show()
plt.plot(weather.index, weather.avgtemp)
plt.title('2015 USA Weather Avg, Max, Min')
plt.ylabel('Avg. Temp.... | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Missing values for weather in days where we have soy quotes | dtMarlon.query('avgtemp.isnull()')
weather.query("date=='2015-06-05' or date=='2015-06-04' or date=='2015-06-03' or date=='2015-06-02' or date=='2015-06-01'")
soybeans.query("Date=='2015-06-05' or Date=='2015-06-04' or Date=='2015-06-03' or Date=='2015-06-02' or Date=='2015-06-01'") | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Filling missing values with method 'ffil'This propagate non-null values forward | dtMarlon = dtMarlon.fillna(method='ffill') | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
Correlation | dtMarlon.corr()
dtMarlon.diff().corr()
pd.plotting.autocorrelation_plot(dtMarlon) | _____no_output_____ | Apache-2.0 | Create_Dataset_MarlonFranco.ipynb | marlonrcfranco/DatasetMarlon |
numpy- ํ๋ ฌ / ์ ํ๋์ / ํต๊ณ ํจํค์ง- ๋จธ์ ๋ฌ๋์ ์ด๋ก ์ ๋ฐฑ๊ทธ๋ผ์ด๋๋ ์ ํ๋์์ ํต๊ณ๋ก ์ด๋ฃจ์ด์ ธ ์๋ค- ์ฌ์ดํท๋ฐ ๊ฐ์ ๋จธ์ ๋ฌ๋ ํจํค์ง๊ฐ ๋ํ์ด ๊ธฐ๋ฐ์ผ๋ก ๋์ด ์๋ค * ๋จธ์ ๋ฌ๋ ์๊ณ ๋ฆฌ์ฆ์ด๋ ์ฌ์ดํ์ด์ ๊ฐ์ ๊ณผํ, ํต๊ณ ์ง์์ฉ ํจํค์ง๋ฅผ ์ง์ ๋ง๋๋ ๊ฐ๋ฐ์ด ์๋๋ผ๋ฉด ๋ํ์ด๋ฅผ ์์ธํ๊ธฐ ์ ํ์๋ ์๋ค์ง๋ง, ๋ํ์ด๋ฅผ ์ดํดํ๋ ๊ฒ์ด ํ์ด์ฌ ๊ธฐ๋ฐ์ ๋ฐ์ดํ๋ถ์๊ณผ ๋จธ์ ๋ฌ๋์ ์ค์ํ๋ค * ๋ํ์ด๊ฐ ๋ฐ์ดํ ํธ๋ค๋ง์ ํจ์จ์ ์ผ๋ก ์ฝ๊ณ ํธํ๊ณ ํ ์ ์๋ค. ๊ทธ๋ฌ๋ ๋ฐ์ดํ ํธ๋ค๋ง์ ์ฃผ๋ก ์ฌ์ฉํ๋ ํ๋ค์ค๋ ๋ง์ ๋ถ๋ถ์ด ๋ํ์ด๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ง๋ค์ด์ ธ ์๋ค. ... | import numpy as np
list_1 = [1, 2, 3]
list_2 = [9, 8, 7]
arr = np.array([list_1, list_2])
arr
print(type(arr))
print(arr.shape)
print(arr.ndim)
# ๋๋ฒ์งธํ์ ๋๋ฒ์งธ ์ด์ ๊ฐ์ 100 ์ง์
arr[[1], 1] = 100
arr
arr1 = np.array([1, 2, 3])
arr2 = np.array([[1, 2, 3]])
print(arr1.shape) # 1์ฐจ์ ํํ๋ก 3๊ฐ์ ์์๋ฅผ ๊ฐ์ง
print(arr2.shape) # 1ํ 3์ด... | (3,)
(1, 3)
1 ์ฐจ์
2 ์ฐจ์
| MIT | jupyter/dAnalysis/b_numpy_class/Ex01_dnarray.ipynb | WoolinChoi/test |
์๋ฃํ | # ์๋ฃํ ํ์ธ
print(type(arr))
# ์์์ ์๋ฃํ ํ์ธ
print(arr.dtype)
# ์์์ ์๋ฃํ ๋ณ๊ฒฝ
arr2 = arr.astype(np.float64)
print(arr2.dtype)
list1 = [1, 2, 3.6]
print(type(list1))
# ndarray ๋ณ๊ฒฝ
list1 = np.array(list1)
print(type(list1))
# ์์
list1.astype(np.float64)
print(list1.dtype)
list2 = [1, 2.3, 'python']
print(type(list2))
# ndarray ๋ณ... | _____no_output_____ | MIT | jupyter/dAnalysis/b_numpy_class/Ex01_dnarray.ipynb | WoolinChoi/test |
nparray๋ฅผ ํธ๋ฆฌํ๊ฒ ์์ฑ* arange() : ๋ฒ์๋ฅผ ์ด์ฉํ ๋ฐฐ์ด ๋ง๋ค๊ธฐ* zeros() : 0์ผ๋ก ์ฑ์ฐ๋ ๋ฐฐ์ด ๋ง๋ค๊ธฐ* ones() : 1๋ก ์ฑ์ฐ๋ ๋ฐฐ์ด ๋ง๋ค๊ธฐ | a = np.arange(10)
print(a)
b = np.arange(1, 11)
print(b)
c = np.arange(1, 11, 3)
print(c)
a2 = np.zeros((5, 5)) # ๊ธฐ๋ณธ์๋ฃํ: float
a2
a3 = np.ones((3, 4), dtype='int32')
a3 | _____no_output_____ | MIT | jupyter/dAnalysis/b_numpy_class/Ex01_dnarray.ipynb | WoolinChoi/test |
ndarray์ ์ฐจ์๊ณผ ํฌ๊ธฐ๋ฅผ ๋ณ๊ฒฝ : reshape() | arr = np.arange(10)
print(arr)
print(arr.shape)
print(arr.ndim) # ์ฐจ์์ผ๋ก ํ์ธ ๊ถ์ฅ
arr2 = arr.reshape(2, 5) # 2ํ 5์ด๋ก ์ฐจ์ํฌ๊ธฐ ๋ณ๊ฒฝ
print(arr2)
print(arr2.shape)
print(arr2.ndim)
# -1 ์ ์ฉ
arr = np.arange(20)
print(arr)
arr2 = arr.reshape(5, -1)
print(arr2)
arr3 = arr.reshape(-1, 2)
print(arr3) | [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]
| MIT | jupyter/dAnalysis/b_numpy_class/Ex01_dnarray.ipynb | WoolinChoi/test |
์ธ๋ฑ์ฑ: ํน์ ๋ฐ์ดํ ์ถ์ถ | #------------------------------------------ (1) ๋จ์ผ๊ฐ ์ถ๋ ฅ
import numpy as np
arr = np.arange(1, 11)
print(arr)
## ์ธ๋ฒ์งธ ์์ ์ถ์ถ ( 0๋ถํฐ ์ธ๋ฑ์ค)
print(arr[3])
## ๋ค์์ ์ธ๋ฒ์งธ ์์ ์ถ์ถ ( ๋ค์์ ์ธ๋ฑ์ค๋ -1๋ถํฐ)
print(arr[-3])
## 1๋ถํฐ 9๊น์ง nparray๋ฅผ ๋ง๋ค๊ณ 3ํ 3์ด 2์ฐจ์ ๊ตฌ์กฐ๋ก ๋ณ๊ฒฝํํ
## ๋๋ฒ์งธ ํ์ ์ธ๋ฒ์งธ ์ด์ ๊ฐ ์ถ์ถ
arr = np.arange(1, 10)
print(arr)
arr2 = arr.reshape(3, 3... | [[1 2 3]
[4 5 6]
[7 8 9]]
[[False False False]
[False False True]
[ True True True]]
| MIT | jupyter/dAnalysis/b_numpy_class/Ex01_dnarray.ipynb | WoolinChoi/test |
Hello PixieDust!This sample notebook provides you with an introduction to many features included in PixieDust. You can find more information about PixieDust at https://ibm-watson-data-lab.github.io/pixiedust/. To ensure you are running the latest version of PixieDust uncomment and run the following cell. Do not run th... | #!pip install --user --upgrade pixiedust | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Import PixieDustRun the following cell to import the PixieDust library. You may need to restart your kernel after importing. Follow the instructions, if any, after running the cell. Note: You must import PixieDust every time you restart your kernel. | import pixiedust | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Enable the Spark Progress MonitorPixieDust includes a Spark Progress Monitor bar that lets you track the status of your Spark jobs. You can find more info at https://ibm-watson-data-lab.github.io/pixiedust/sparkmonitor.html. Run the following cell to enable the Spark Progress Monitor: | pixiedust.enableJobMonitor(); | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Example use of the PackageManagerYou can use the PackageManager component of Pixiedust to install and uninstall maven packages into your notebook kernel without editing configuration files. This component is essential when you run notebooks from a hosted cloud environment and do not have access to the configuration fi... | pixiedust.installPackage("graphframes:graphframes:0.1.0-spark1.6")
print("done") | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Run the following cell to print out all installed packages: | pixiedust.printAllPackages() | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Example use of the display() APIPixieDust lets you visualize your data in just a few clicks using the display() API. You can find more info at https://ibm-watson-data-lab.github.io/pixiedust/displayapi.html. The following cell creates a DataFrame and uses the display() API to create a bar chart: | sqlContext=SQLContext(sc)
d1 = sqlContext.createDataFrame(
[(2010, 'Camping Equipment', 3),
(2010, 'Golf Equipment', 1),
(2010, 'Mountaineering Equipment', 1),
(2010, 'Outdoor Protection', 2),
(2010, 'Personal Accessories', 2),
(2011, 'Camping Equipment', 4),
(2011, 'Golf Equipment', 5),
(2011, 'Mountaineering E... | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Example use of the Scala bridgeData scientists working with Spark may occasionaly need to call out to one of the hundreds of libraries available on spark-packages.org which are written in Scala or Java. PixieDust provides a solution to this problem by letting users directly write and run scala code in its own cell. It... | python_var = "Hello From Python"
python_num = 10 | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Create scala code that use the python_var and create a new variable that we'll use in Python: | %%scala
println(python_var)
println(python_num+10)
val __scala_var = "Hello From Scala" | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Use the __scala_var from python: | print(__scala_var) | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Sample DataPixieDust includes a number of sample data sets. You can use these sample data sets to start playing with the display() API and other PixieDust features. You can find more info at https://ibm-watson-data-lab.github.io/pixiedust/loaddata.html. Run the following cell to view the available data sets: | pixiedust.sampleData() | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Example use of sample dataTo use sample data locally run the following cell to install required packages. You may need to restart your kernel after running this cell. | pixiedust.installPackage("com.databricks:spark-csv_2.10:1.5.0")
pixiedust.installPackage("org.apache.commons:commons-csv:0") | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.