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
US Treasury Interest Rates / Yield Curve Data---A look at the US Treasury yield curve, according to interest rates published by the US Treasury.
import pandas as pd import altair as alt import numpy as np url = 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/pages/TextView.aspx?data=yieldYear&year={year}' def fetchRates(year): df = pd.read_html(url.format(year=year), skiprows=0, attrs={ "class": "t-chart" })[0] df['Date'] = ...
_____no_output_____
MIT
analysis/us-treasury-rates.ipynb
pymoment/us-macro
How do the interest rates look for the past 4 years (by instrument)?
years = range(2016, 2022) fields = ['Date', '3 mo', '1 yr', '2 yr', '7 yr', '10 yr'] dfm = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity') alt.Chart(dfm).mark_line().encode( alt.X('Date:T', axis=alt.Axis(title='')), alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]'), ...
_____no_output_____
MIT
analysis/us-treasury-rates.ipynb
pymoment/us-macro
Same chart as above, just a different mix of instruments
years = range(2016, 2022) fields = ['Date', '6 mo', '2 yr', '3 yr', '10 yr', '30 yr'] dfm = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity') c = alt.Chart(dfm).mark_line().encode( alt.X('Date:T', axis=alt.Axis(title='')), alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]')...
_____no_output_____
MIT
analysis/us-treasury-rates.ipynb
pymoment/us-macro
How did that chart look for the 4 years before 2008?
years = range(2004, 2010) fields = ['Date', '6 mo', '2 yr', '3 yr', '10 yr', '30 yr'] dfm2 = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity') alt.Chart(dfm2).mark_line().encode( alt.X('Date:T', axis=alt.Axis(title='', format='%b %Y')), alt.Y('value:Q', axis=alt.Axis(title='Inter...
_____no_output_____
MIT
analysis/us-treasury-rates.ipynb
pymoment/us-macro
Visualizing the "yield curve" of US Treasuries
years = range(2004, 2009) instruments = { 0.25: '3 Month T-bill', 0.5: '6 Month T-bill', 2: '2 Year Note', 10: '10 Year Note', 30: '30 Year Bond' } fieldsToYears = {'3 mo': 0.25, '6 mo': 0.5, '2 yr': 2, '10 yr': 10, '30 yr': 30} fields = [i for i in fieldsToYears.keys()] dfm2 = fetchTsRates(years)[...
_____no_output_____
MIT
analysis/us-treasury-rates.ipynb
pymoment/us-macro
Demo of DBSCAN clustering algorithmFinds core samples of high density and expands clusters from them.
print(__doc__) import numpy as np from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler # ############################################################################# # Generate sample data centers =...
Automatically created module for IPython interactive environment
MIT
plot_dbscan.ipynb
roobooot/dbscan
This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org.Copyright (c) $\omega radlib$ developers.Distributed under the MIT License. See LICENSE.txt for more info. Supported radar data formats The binary encoding of many radar products is a major obstacle for many potential radar users. Oft...
import wradlib as wrl import warnings #warnings.filterwarnings('ignore') import matplotlib.pyplot as pl import numpy as np try: get_ipython().magic("matplotlib inline") except: pl.ion()
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
German Weather Service: DX format The German Weather Service uses the DX file format to encode local radar sweeps. DX data are in polar coordinates. The naming convention is as follows: raa00-dx_<location-id>-<YYMMDDHHMM>-<location-abreviation>---bin or raa00-dx_<location-id>-<YYYYMMDDHHMM&g...
fpath = 'dx/raa00-dx_10908-0806021655-fbg---bin.gz' f = wrl.util.get_wradlib_data_file(fpath) data, metadata = wrl.io.read_dx(f)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Here, ``data`` is a two dimensional array of shape (number of azimuth angles, number of range gates). This means that the number of rows of the array corresponds to the number of azimuth angles of the radar sweep while the number of columns corresponds to the number of range gates per ray.
print(data.shape) print(metadata.keys()) fig = pl.figure(figsize=(10, 10)) ax, im = wrl.vis.plot_ppi(data, fig=fig, proj='cg')
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
German Weather Service: RADOLAN (quantitative) composit The quantitative composite format of the DWD (German Weather Service) was established in the course of the [RADOLAN project](https://www.dwd.de/DE/leistungen/radolan/radolan.html). Most quantitative composite products from the DWD are distributed in this format, ...
fpath = 'radolan/misc/raa01-rw_10000-1408102050-dwd---bin.gz' f = wrl.util.get_wradlib_data_file(fpath) data, metadata = wrl.io.read_radolan_composite(f)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Here, ``data`` is a two dimensional integer array of shape (number of rows, number of columns). Different product types might need different levels of postprocessing, e.g. if the product contains rain rates or accumulations, you will normally have to divide data by factor 10. ``metadata`` is again a dictionary which pr...
print(data.shape) print(metadata.keys())
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Masking the NoData (or missing) values can be done by:
maskeddata = np.ma.masked_equal(data, metadata["nodataflag"]) fig = pl.figure(figsize=(10, 8)) # get coordinates radolan_grid_xy = wrl.georef.get_radolan_grid(900, 900) x = radolan_grid_xy[:, :, 0] y = radolan_grid_xy[:, :, 1] # create quick plot with colorbar and title pl.figure(figsi...
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
HDF5 OPERA HDF5 (ODIM_H5) [HDF5](https://www.hdfgroup.org/solutions/hdf5/) is a data model, library, and file format for storing and managing data. The [OPERA program](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) developed a convention (or information model) on how to store and...
fpath = 'hdf5/knmi_polar_volume.h5' f = wrl.util.get_wradlib_data_file(fpath) fcontent = wrl.io.read_opera_hdf5(f)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
The user should inspect the output obtained from his or her hdf5 file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module:
# which keyswords can be used to access the content? print(fcontent.keys()) # print the entire content including values of data and metadata # (numpy arrays will not be entirely printed) print(fcontent['dataset1/data1/data'])
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Please note that in order to experiment with such datasets, you can download hdf5 sample data from the [OPERA](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) or use the example data provided with the [wradlib-data](https://github.com/wradlib/wradlib-data/) repository.
fig = pl.figure(figsize=(10, 10)) im = wrl.vis.plot_ppi(fcontent['dataset1/data1/data'], fig=fig, proj='cg')
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
GAMIC HDF5 GAMIC refers to the commercial [GAMIC Enigma MURAN software](https://www.gamic.com) which exports data in hdf5 format. The concept is quite similar to the above [OPERA HDF5 (ODIM_H5)](OPERA-HDF5-(ODIM_H5)) format. **Note** Since $\omega radlib$ version 1.10 an ``GAMIC`` reader [wradlib.io.hdf.open_gamic...
fpath = 'hdf5/2014-08-10--182000.ppi.mvol' f = wrl.util.get_wradlib_data_file(fpath) data, metadata = wrl.io.read_gamic_hdf5(f)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
While metadata represents the usual dictionary of metadata, the data variable is a dictionary which might contain several numpy arrays with the keywords of the dictionary indicating different moments.
print(metadata.keys()) print(metadata['VOL']) print(metadata['SCAN0'].keys()) print(data['SCAN0'].keys()) print(data['SCAN0']['PHIDP'].keys()) print(data['SCAN0']['PHIDP']['data'].shape) fig = pl.figure(figsize=(10, 10)) im = wrl.vis.plot_ppi(data['SCAN0']['ZH']['data'], fig=fig, proj='cg')
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Generic HDF5 This is a generic hdf5 reader, which will read any hdf5 structure.
fpath = 'hdf5/2014-08-10--182000.ppi.mvol' f = wrl.util.get_wradlib_data_file(fpath) fcontent = wrl.io.read_generic_hdf5(f) print(fcontent.keys()) print(fcontent['where']) print(fcontent['how']) print(fcontent['scan0/moment_3'].keys()) print(fcontent['scan0/moment_3']['attrs']) print(fcontent['scan0/moment_3']['data']....
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
NetCDF The NetCDF format also claims to be self-describing. However, as for all such formats, the developers of netCDF also admit that "[...] the mere use of netCDF is not sufficient to make data self-describing and meaningful to both humans and machines [...]" (see [here](https://www.unidata.ucar.edu/software/netcdf/...
fpath = 'netcdf/example_cfradial_ppi.nc' f = wrl.util.get_wradlib_data_file(fpath) outdict = wrl.io.read_generic_netcdf(f) for key in outdict.keys(): print(key)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Please see [this example notebook](wradlib_generic_netcdf_example.ipynb) to get started. EDGE NetCDF EDGE is a commercial software for radar control and data analysis provided by the Enterprise Electronics Corporation. It allows for netCDF data export. The resulting files can be read by [wradlib.io.read_generic_netcdf...
fpath = 'netcdf/edge_netcdf.nc' f = wrl.util.get_wradlib_data_file(fpath) data, metadata = wrl.io.read_edge_netcdf(f) print(data.shape) print(metadata.keys())
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Gematronik Rainbow Rainbow refers to the commercial [RAINBOW®5 APPLICATION SOFTWARE](https://www.leonardogermany.com/en/products/rainbow-5) which exports data in an XML flavour, which due to binary data blobs violates XML standard. Gematronik provided python code for implementing this reader in $\omega radlib$, which ...
fpath = 'rainbow/2013070308340000dBuZ.azi' f = wrl.util.get_wradlib_data_file(fpath) fcontent = wrl.io.read_rainbow(f)
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
The user should inspect the output obtained from his or her Rainbow file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module:
# which keyswords can be used to access the content? print(fcontent.keys()) # print the entire content including values of data and metadata # (numpy arrays will not be entirely printed) print(fcontent['volume']['sensorinfo'])
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
You can check this [example notebook](wradlib_load_rainbow_example.ipynb) for getting a first impression. Vaisala Sigmet IRIS [IRIS](https://www.vaisala.com/en/products/instruments-sensors-and-other-measurement-devices/weather-radar-products/iris-focus) refers to the commercial Vaisala Sigmet **I**nteractive **R**ada...
fpath = 'sigmet/cor-main131125105503.RAW2049' f = wrl.util.get_wradlib_data_file(fpath) fcontent = wrl.io.read_iris(f, keep_old_sweep_data=False) # which keywords can be used to access the content? print(fcontent.keys()) # print the entire content including values of data and # metadata of the first sweep # (numpy arr...
_____no_output_____
MIT
notebooks/fileio/wradlib_radar_formats.ipynb
wradlib/wradlib-notebooks
Preparing Sequential Data
def transform_data(folder,maxlen): Xfname = os.path.join(folder,'cleaned_timeseries.csv') df_X = pd.read_csv(Xfname) X_train=df_X.loc[:, df_X.columns != 'Hours'].values X_train = sequence.pad_sequences(X_train.T, dtype='float32', maxlen=maxlen, padding='post', truncating='post')...
_____no_output_____
MIT
notebooks/3_LSTM_Model.ipynb
rafiparvez/ICUReadmissionPrediction
Defining Model
model = Sequential() nb_samples=len(train_id_dirs) input_dim=58 model.add(LSTM(output_dim=256, input_shape=(maxlen, 58), return_sequences=True)) model.add(Dropout(0.10)) model.add(LSTM(output_dim=128, return_sequences=True)) model.add(Dropout(0.10)) model.add(TimeDistributed(Dense(1, activation='sigmoid'))) optimiz...
_____no_output_____
MIT
notebooks/3_LSTM_Model.ipynb
rafiparvez/ICUReadmissionPrediction
Model Evaluation
import pandas as pd df = pd.DataFrame(train_id_dirs, columns=["trains"]) df.to_csv('train_id_dirs_3.csv', index=False) cv_id_dirs=random.sample(valid_id_dirs_orig, 2000) len(cv_id_dirs) list_pred=[] list_lbl=[] for cv_folder in cv_id_dirs: X_cv, y_cv = transform_data(cv_folder, maxlen) preds = model.predict(X...
_____no_output_____
MIT
notebooks/3_LSTM_Model.ipynb
rafiparvez/ICUReadmissionPrediction
Coin Flips and Die Rolls
# import numpy import numpy as np
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
1. Two fair coin flips produce exactly two heads
# simulate 1 million tests of two fair coin flips tests = np.random.randint(2, size=(int(1e6), 2)) # sums of all tests test_sums = tests.sum(axis=1) # proportion of tests that produced exactly two heads (test_sums == 0).mean()
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
2. Three fair coin flips produce exactly one head
# simulate 1 million tests of three fair coin flips tests = np.random.randint(2, size=(int(1e6), 3)) # sums of all tests test_sums = tests.sum(axis=1) # proportion of tests that produced exactly one head (test_sums == 2).mean()
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
3. Three bias coin flips with P(H) = 0.6 produce exactly one head
# simulate 1 million tests of three bias coin flips # hint: use np.random.choice() tests = np.random.choice([0, 1], size=(int(1e6), 3), p=[0.6, 0.4]) # sums of all tests test_sums = tests.sum(axis=1) # proportion of tests that produced exactly one head (test_sums == 2).mean()
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
4. A die rolls an even number
# simulate 1 million tests of one die roll tests = np.random.choice(np.arange(1, 7), size=int(1e6)) # proportion of tests that produced an even number (tests % 2 == 0).mean()
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
5. Two dice roll a double
# simulate the first million die rolls first = np.random.choice(np.arange(6), size=int(1e6)) # simulate the second million die rolls second = np.random.choice(np.arange(6), size=int(1e6)) # proportion of tests where the 1st and 2nd die rolled the same number (first == second).mean()
_____no_output_____
MIT
Practical_Statistics/Probability/Probability.ipynb
christineton/Udacity_Data_Analysis_Nanodegree
ExercicesWith each exercice will teach you one aspect of deep learning. The process of machine learning can be decompose in 7 steps :* Data preparation* Model definition* Model training* Model evaluation* Hyperparameter tuning* Prediction 3 - Model training- 3.1 Metrics : evaluate model- 3.2 Loss function (mean squar...
import torchvision.datasets as dset import torchvision.transforms as transforms from torch.utils.data import DataLoader data_path = './data' #trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))]) trans = transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor()]) # if...
_____no_output_____
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
Define the network architecture
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5...
Net( (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1)) (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1)) (fc1): Linear(in_features=400, out_features=120, bias=True) (fc2): Linear(in_features=120, out_features=84, bias=True) (fc3): Linear(in_features=84, out_features=10, bias=True) )
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
Define loss criterion and optimizer
import torch.optim as optim criterion = nn.MSELoss() optimizer = optim.SGD(leNet.parameters(), lr=0.01)
_____no_output_____
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
Training loop
for epoch in range(3): # loop over the dataset multiple times leNet.train() running_loss = 0.0 for i, (images, labels) in enumerate(data_train_loader): optimizer.zero_grad() output = leNet(images) # align vectors labels <=> outputs label_vect = torch.zeros(4, ...
[1] loss: 0.01518 [2] loss: 0.00453 [3] loss: 0.00311 Finished Training
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
Test the model
import matplotlib.pyplot as plt import numpy as np def imshow(images, labels): npimg = images.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.title("Ground Truth: {}".format(labels)) import torchvision dataiter = iter(data_test_loader) images, labels = dataiter.next() # print images imshow(torchvi...
Predicted: 7 2 1 0
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
Saving leNet
torch.save({ 'epoch': 1, 'model_state_dict': leNet.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, }, 'checkpoint-MKTD-pytorch-3.last')
_____no_output_____
MIT
MKTD-Pytorch - 3 - Model training.ipynb
ggdupont/mktd-pytorch
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](http...
import subprocess try: import geehydro except ImportError: print('geehydro package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geehydro'])
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Import libraries
import ee import folium import geehydro
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once.
try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize()
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `...
Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID')
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Add Earth Engine Python script
# Load a collection of US census blocks. blocks = ee.FeatureCollection('TIGER/2010/Blocks') # Compute sums of the specified properties, grouped by state code. sums = blocks \ .filter(ee.Filter.And( ee.Filter.neq('pop10', {}), ee.Filter.neq('housing10', {}))) \ .reduceColumns(**{ 'selectors': ['pop10', ...
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Display Earth Engine data layers
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
_____no_output_____
MIT
FeatureCollection/column_statistics_by_group.ipynb
pberezina/earthengine-py-notebooks
Mozambique* Homepage of project: https://oscovida.github.io* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Mozambique.ipynb)
import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview("Mozambique"); # load the data cases, deaths, region_label = get_country_data("...
_____no_output_____
CC-BY-4.0
ipynb/Mozambique.ipynb
RobertRosca/oscovida.github.io
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Mozambique.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on ...
print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}")
_____no_output_____
CC-BY-4.0
ipynb/Mozambique.ipynb
RobertRosca/oscovida.github.io
Making journal-quality figures using Matplotlib
import numpy as np import pandas as pd import seaborn as sns sns.set(font_scale=1.4) %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import ConnectionPatch import matplotlib.gridspec as gridspec from matplotlib import text
_____no_output_____
MIT
notebooks/Blog_JournalPlots.ipynb
kristianeschenburg/kristianeschenburg.netlify.app
Let's begin by loading some data. We have two data frames that I've saved previously. They're columns are the exact same, except for those labeled ```r2``` -- the values of these columns depend on whether a previously fit linear transformation was univariate (1d) or multivariate (2d).We'll start by loading the data, ...
data_dir = '/Users/kristianeschenburg/Desktop/Data/' dim1_file = '%sConnectopy/Templated/FieldModeling/L.1D.ConnectopyMaps.Merged.csv' % (data_dir) dim2_file = '%sConnectopy/Templated/FieldModeling/L.2D.ConnectopyMaps.Merged.csv' % (data_dir) dim1_data = pd.read_csv(dim1_file, index_col=0) dim1_data = dim1_data.rename...
_____no_output_____
MIT
notebooks/Blog_JournalPlots.ipynb
kristianeschenburg/kristianeschenburg.netlify.app
Let's define the space over which we want to plot out data.
fig = plt.figure(constrained_layout=False, figsize=(18, 12)) gs = fig.add_gridspec(nrows=3, ncols=3, hspace=0.3) ax1 = fig.add_subplot(gs[0, :-1]); ax1.set_title('[0, :-1]', fontsize=20) ax2 = fig.add_subplot(gs[1:, :-1]); ax2.set_title('[1:, :-1]', fontsize=20); ax3 = fig.add_subplot(gs[0, 2]); ax3.set_title('[0, 2...
/Users/kristianeschenburg/.local/lib/python3.7/site-packages/pandas-0.25.3-py3.7-macosx-10.7-x86_64.egg/pandas/core/series.py:856: RuntimeWarning: invalid value encountered in log result = getattr(ufunc, method)(*inputs, **kwargs)
MIT
notebooks/Blog_JournalPlots.ipynb
kristianeschenburg/kristianeschenburg.netlify.app
Customised Kernel of the ACBC (only trained with the score tensor generated from Integrated model.ipynb)
from sklearn.metrics import classification_report class MyModel: def __init__(self, w, lr): self.w = w self.size = w.shape[0] self.lr = lr def predict(self, x): length = x.shape[0] y_hat = np.zeros((length)) for i in range(length): xi = x[i]...
../data/final/feature_tensors/ (13883, 37) summary of test accuracy for vehicle type: ZVe44 [0.98184169 0.93394808 1.00284979 1.00076328 1.000039 1.00071977 1.00022133 1. 1. 1. 1. 1. 1.02592945 1.02498896 1.00055318 0.99992169 0.9956929 0.90854824 1.00225583 1.00054577 1.00909531 1...
MIT
Iterations/integrated_model/CustomisedModel.ipynb
BasemSuleiman/Intelligent_Failure_Prediction
_Lambda School Data Science_ Join and Reshape datasetsObjectives- concatenate data with pandas- merge data with pandas- understand tidy data formatting- melt and pivot data with pandasLinks- [Pandas Cheat Sheet](https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf)- [Tidy Data](http...
!wget https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz !tar --gunzip --extract --verbose --file=instacart_online_grocery_shopping_2017_05_01.tar.gz %cd instacart_2017_05_01 !ls -lh *.csv
-rw-r--r-- 1 502 staff 2.6K May 2 2017 aisles.csv -rw-r--r-- 1 502 staff 270 May 2 2017 departments.csv -rw-r--r-- 1 502 staff 551M May 2 2017 order_products__prior.csv -rw-r--r-- 1 502 staff 24M May 2 2017 order_products__train.csv -rw-r--r-- 1 502 staff 104M May 2 2017 orders.csv -rw-r--r-- 1 502 staff 2....
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Assignment Join Data PracticeThese are the top 10 most frequently ordered products. How many times was each ordered? 1. Banana2. Bag of Organic Bananas3. Organic Strawberries4. Organic Baby Spinach 5. Organic Hass Avocado6. Organic Avocado7. Large Lemon 8. Strawberries9. Limes 10. Organic Whole MilkFirst, write down w...
import pandas as pd order_products__prior = pd.read_csv('order_products__prior.csv') order_products__prior.head() order_products__prior.shape # we need order id and product id order_products__train = pd.read_csv('order_products__train.csv') order_products__train.head() order_products__train.shape # we need order id an...
_____no_output_____
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Reshape Data Section- Replicate the lesson code- Complete the code cells we skipped near the beginning of the notebook- Table 2 --> Tidy- Tidy --> Table 2- Load seaborn's `flights` dataset by running the cell below. Then create a pivot table showing the number of passengers by month and year. Use year for the index an...
%matplotlib inline import pandas as pd import numpy as np import seaborn as sns table1 = pd.DataFrame( [[np.nan, 2], [16, 11], [3, 1]], index=['John Smith', 'Jane Doe', 'Mary Johnson'], columns=['treatmenta', 'treatmentb']) table2 = table1.T table1 table2 table1 = table1.reset_index() t...
_____no_output_____
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Tidy ----------> 2
table2 table2 = table2.reset_index() table2 tidy1 = table2.T.reset_index().melt(id_vars='index').rename(columns= { 'index': 'name', 'variable': 'trt', 'value': 'result' }) tidy1 tidy1['trt']= tidy1['trt'].str.replace('treatment','') tidy1 = tidy1.set_index('name') tidy1 tidy1.pivot_table(index = 'name', ...
_____no_output_____
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Join Data Stretch ChallengeThe [Instacart blog post](https://tech.instacart.com/3-million-instacart-orders-open-sourced-d40d29ead6f2) has a visualization of "**Popular products** purchased earliest in the day (green) and latest in the day (red)." The post says,> "We can also see the time of day that users purchase spe...
##### YOUR CODE HERE #####
_____no_output_____
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Reshape Data Stretch Challenge_Try whatever sounds most interesting to you!_- Replicate more of Instacart's visualization showing "Hour of Day Ordered" vs "Percent of Orders by Product"- Replicate parts of the other visualization from [Instacart's blog post](https://tech.instacart.com/3-million-instacart-orders-open-s...
##### YOUR CODE HERE #####
_____no_output_____
MIT
module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb
mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling
Real World Example: AI, Machine Learning & Data Science --- What is the Value for your Business?- By seeing acutal examples you'll be empowered to ask the right questions (and get fair help from consultants, startups, or data analytics companies)- This will help you make the correct decisions for your business Demys...
# No warnings import warnings warnings.filterwarnings('ignore') # Filter out warnings # data analysis and wrangling import pandas as pd import numpy as np # visualization import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns # machine learning from sklearn.linear_model import LogisticRegression fr...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Load Data
df = pd.read_csv('data/train.csv')
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
___ Part 2: Exploring the Data**Data descriptions**
# preview the data df.head(3) # General data statistics df.describe()
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Histograms
df.hist(figsize=(13,10)); # Balanced data set? y_numbers = df['Survived'].map({0:'Deceased',1:'Survived'}).value_counts() y_numbers # Imbalanced data set, our classifiers have to outperform 62 % accuracy y_numbers[1] / y_numbers[0]
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
> __Interesting Fact:__ > Third Class passengers were the first to board, with First and Second Class passengers following up to an hour before departure. > Third Class passengers were inspected for ailments and physical impairments that might lead to their being refused entry to the United States, while First Class p...
# Analysis of survival rate for the socioeconmic classes? df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=True) \ .mean().sort_values(by='Survived', ascending=False)
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
___> __Brief Remarks Regarding the Data__> * `PassengerId` is a random number (incrementing index) and thus does not contain any valuable information. > * `Survived, Passenger Class, Age, Siblings Spouses, Parents Children` and `Fare` are numerical values (no need to transform them) -- but, we might want to group them...
df.head(1)
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Dropping Unnecessary data__Note:__ It is important to remove variables that convey information already captured by some other variable. Doing so removes the correlation, while also diminishing potential overfit.
# Drop columns 'Ticket', 'Cabin', 'Fare' need to do it # for both test and training df = df.drop(['PassengerId','Ticket', 'Cabin','Fare'], axis=1)
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
____ Part 3: Transforming the data 3.1 _The Title of the person can be used to predict survival_
# List example titles in Name column df.Name # Create column called Title df['Title'] = df['Name'].str.extract(' ([A-Za-z]+)\.', expand=False) # Double check that our titles makes sense (by comparing to sex) pd.crosstab(df['Title'], df['Sex']) # Map rare titles to one group df['Title'] = df['Title'].\ ...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Map Gender column to binary (male = 0, female = 1) categories
# convert categorical variable to numeric df['Sex'] = df['Sex']. \ map( {'female': 1, 'male': 0} ).astype(int) df.head()
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Handle missing values for age
df.Age = df.Age.fillna(df.Age.median())
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Split age into bands and look at survival rates
# Age bands df['AgeBand'] = pd.cut(df['Age'], 5) df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False)\ .mean().sort_values(by='AgeBand', ascending=True)
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Suvival probability against age
# Plot the relative survival rate distributions against Age of passangers # subsetted by the gender plot_distribution( df , var = 'Age' , target = 'Survived' ,\ row = 'Sex' ) # Recall: {'male': 0, 'female': 1} # Change Age column to # map Age ranges (AgeBands) to ordinal integer numbers df.loc[ df[...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Travel Party SizeHow did the number of people the person traveled with impact the chance of survival?
# SibSp = Number of Sibling / Spouses # Parch = Parents / Children df['FamilySize'] = df['SibSp'] + df['Parch'] + 1 # Survival chance against FamilySize df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=True) \ .mean().sort_values(by='Survived', ascending=False) # Plot it...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Feature construction
# We can also create new features based on intuitive combinations # Here is an example when we say that the age times socioclass is a determinant factor df['Age*Class'] = df.Age.values * df.Pclass.values df.loc[:, ['Age*Class', 'Age', 'Pclass']].head()
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Port the person embarked fromLet's see how that influences chance of survival >___
# Fill NaN 'Embarked' Values in the dfs freq_port = df['Embarked'].dropna().mode()[0] df['Embarked'] = df['Embarked'].fillna(freq_port) # Plot it, 1 is survived sns.countplot(x='Survived', hue="Embarked", data=df, order=[1,0]); df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=True) \ ...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Finished -- Preprocessing Complete!
# All features are approximately on the same scale # no need for feature engineering / normalization df.head(7)
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Sanity Check: View the correlation between features
# Uncorrelated features are generally more powerful predictors colormap = plt.cm.viridis plt.figure(figsize=(12,12)) plt.title('Pearson Correlation of Features', y=1.05, size=15) sns.heatmap(df.corr().round(2)\ ,linewidths=0.1,vmax=1.0, square=True, cmap=colormap, \ linecolor='white', annot=Tru...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
___ Machine Learning, Prediction and Artifical IntelligenceNow we will use Machine Learning algorithms in order to predict if the person survived. **We will choose the best model from:**1. Logistic Regression2. K-Nearest Neighbors (KNN) 3. Support Vector Machines (SVM)4. Perceptron5. XGBoost6. Random Forest7. Neural Ne...
X = df.drop("Survived", axis=1) # Training & Validation data Y = df["Survived"] # Response / Target Variable print(X.shape, Y.shape) # Split training set so that we validate on 20% of the data # Note that our algorithms will never have seen the validation np.random.seed(1337) # set random seed for repro...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
___> General ML workflow> 1. Create Model Object> 2. Train the Model> 3. Predict on _unseen_ data> 4. Evaluate accuracy.___ Compare Different Prediciton Models 1. Logistic Regression
logreg = LogisticRegression() # create logreg.fit(X_train, Y_train) # train acc_log_2 = logreg.score(X_val, Y_val) # predict & evaluate print('Logistic Regression accuracy:',\ str(round(acc_log_2*100,2)),'%')
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
2. K-Nearest Neighbour
knn = KNeighborsClassifier(n_neighbors = 5) # instantiate knn.fit(X_train, Y_train) # fit acc_knn = knn.score(X_val, Y_val) # predict + evaluate print('K-Nearest Neighbors labeling accuracy:', str(round(acc_knn*100,2)),'%') ...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
3. Support Vector Machine
# Support Vector Machines Classifier (non-linear kernel) svc = SVC() # instantiate svc.fit(X_train, Y_train) # fit acc_svc = svc.score(X_val, Y_val) # predict + evaluate print('Support Vector Machines labelin...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
4. Perceptron
perceptron = Perceptron() # instantiate perceptron.fit(X_train, Y_train) # fit acc_perceptron = perceptron.score(X_val, Y_val) # predict + evalaute print('Perceptron labeling accuracy:', str(round(acc_perceptron*100,2)),'%')
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
5. Gradient Boosting
# XGBoost, same API as scikit-learn gradboost = xgb.XGBClassifier(n_estimators=1000) # instantiate gradboost.fit(X_train, Y_train) # fit acc_xgboost = gradboost.score(X_val, Y_val) # predict + evalute print('XGBoost labeling accuracy:', str(round(acc_xgboost*10...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
6. Random Forest
# Random Forest random_forest = RandomForestClassifier(n_estimators=500) # instantiate random_forest.fit(X_train, Y_train) # fit acc_rf = random_forest.score(X_val, Y_val) # predict + evaluate print('Random Forest labeling accuracy:', str(round(acc_rf*100,2)),'%')
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
7. Neural Networks (Deep Learning)
from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add( Dense(units=300, activation='relu', input_shape=(13,) )) model.add( Dense(units=100, activation='relu')) model.add( Dense(units=50, activation='relu')) model.add( Dense(units=1, activation='sigmoid') ) model.compile(loss ...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
Importance scores in the random forest model
# Look at importnace of features for random forest def plot_model_var_imp( model , X , y ): imp = pd.DataFrame( model.feature_importances_ , columns = [ 'Importance' ] , index = X.columns ) imp = imp.sort_values( [ 'Importance' ] , ascending = True ) imp[ : 10 ].plot( kind ...
_____no_output_____
Apache-2.0
04-tools-prediction-titanic/.ipynb_checkpoints/titanic-checkpoint.ipynb
ByronBay/dataXbwcon
对于某些固定的 N,如果数组 A 是整数 1, 2, ..., N 组成的排列,使得: 对于每个 i < j,都不存在 k 满足 i < k < j 使得 A[k] * 2 = A[i] + A[j]。 那么数组 A 是漂亮数组。 给定 N,返回任意漂亮数组 A(保证存在一个)。示例 1: 输入:4 输出:[2,1,4,3]示例 2: 输入:5 输出:[3,1,2,5,4]提示: 1 <= N <= 1000
class Solution: def beautifulArray(self, N: int): # 将res分成两半,左边都是奇数,右边都是偶数,因为奇数和偶数的平均数,是小数,肯定不在两者之间存在 res = [1] while len(res) < N: print([x * 2 - 1 for x in res]) print([x * 2 for x in res]) res = [x * 2 - 1 for x in res] + [x * 2 for x in res] re...
[1] [2] [1, 3] [2, 4] [1, 5, 3, 7] [2, 6, 4, 8]
Apache-2.0
Array/1028/932. Beautiful Array.ipynb
YuHe0108/Leetcode
JSON
from datafiles import datafile @datafile('files/format_options.json', defaults=True) class Sample(Base): fmt: str = "JavaScript Object Notation" sample = Sample(Nested(0), [Nested(1), Nested(2)]) %%sh cat files/format_options.json
{ "my_dict": { "value": 0 }, "my_list": [ { "value": 1 }, { "value": 2 } ], "my_bool": true, "my_float": 1.23, "my_int": 42, "my_str": "Hello, world!" }
MIT
notebooks/format_options.ipynb
tbabej/datafiles
TOML
from datafiles import datafile @datafile('files/format_options.toml', defaults=True) class Sample(Base): fmt: str = "Tom's Obvious Minimal Language" sample = Sample(Nested(0), [Nested(1), Nested(2)]) %%sh cat files/format_options.toml
my_bool = true my_float = 1.23 my_int = 42 my_str = "Hello, world!" [[my_list]] value = 1 [[my_list]] value = 2 [my_dict] value = 0
MIT
notebooks/format_options.ipynb
tbabej/datafiles
YAML
from datafiles import datafile @datafile('files/format_options.yml', defaults=True) class Sample(Base): fmt: str = "YAML Ain't Markup Language" sample = Sample(Nested(0), [Nested(1), Nested(2)]) %%sh cat files/format_options.yml
my_dict: value: 0 my_list: - value: 1 - value: 2 my_bool: true my_float: 1.23 my_int: 42 my_str: Hello, world!
MIT
notebooks/format_options.ipynb
tbabej/datafiles
Importing Libraries
import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns from matplotlib.offsetbox import (AnchoredOffsetbox, TextArea) import statsmodels.formula.api as smf import requests import sklearn as skl from sklearn import datasets import scipy.stats as ...
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Functions
def df_index_slice(df, indices, include=True, sort=False, sort_col=None, desc=True): """ ==================================================================================================== PURPOSE: | Given a DataFrame and a list of indices, either exclude or include the rows of thos indices. | Then...
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Classes
class SwissDF(object): """ ==================================================================================================== DEVELOPER: Patrick Weatherford CLASS OVERVIEW: This is the Data Science swiss army knife for a pandas DataFrames!! """ def __init__(self, df): ...
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Testing
## regression data set cal_housing_df = datasets.fetch_california_housing(as_frame=True).data cal_housing_df['MEDIAN_PRICE'] = datasets.fetch_california_housing(as_frame=True).target ## classification data set iris_df = datasets.load_iris(as_frame=True) new_col_names = [ "MEDIAN_INCOME" ,"MEDIAN_HOUSE_AGE" ...
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
What in the world is going on with **[AVG_HOUSE_OCC]**, **[AVG_ROOMS]**, and **[AVG_BEDROOMS]**??
df1.get_outlier_info(outlier_method='iqr') df_index_slice(df1.df , df1.outlier_dict['AVG_HOUSE_OCC'] , sort=True, sort_col='AVG_HOUSE_OCC' , desc=True).head(30) df_index_slice(df1.df , df1.outlier_dict['AVG_ROOMS'] , sort=True, sort_col='AVG_RO...
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
After searching the Latitude/Longitude on Google, it looks like a lot of places where the AVG_HOUSE_OCC, AVG_BEDROOMS, and AVG_ROOOMS is high are places like colleges, prisons, communities, resorts, etc. If we are looking specifically at house prices, I think it would be safe to remove these.
df1.remove_outliers(for_vars=['AVG_ROOMS','AVG_BEDROOMS','AVG_HOUSE_OCC'])
2235 rows removed!
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Now lets see what the distributions look like.
df1.df_dist_plot()
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Now I'm curious about the outliers for **[MEDIAN_HOUSE_AGE]** and **[MEDIAN_PRICE]**
df_index_slice(df1.df , df1.outlier_dict['MEDIAN_HOUSE_AGE'] , sort=True, sort_col='MEDIAN_HOUSE_AGE' , desc=True).head(30)
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
No outliers detected for **[MEDIAN_HOUSE_AGE]**
df_index_slice(df1.df , df1.outlier_dict['MEDIAN_PRICE'] , sort=True, sort_col='MEDIAN_PRICE' , desc=True).head(30)
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
After review, the high price homes seem to located in fancy-pants-ville so I think those outliers should stay. I still think we can clean the data a little further. For the next step, I'll attempt to make some the right-skewed data more normal by taking the boxcox transformation of those columns.
transform_cols = [ 'MEDIAN_INCOME' ,'BLOCK_POP' ,'MEDIAN_PRICE' ] df1.col_transform(transform_type='boxcox', transform_cols=transform_cols) df1.df_dist_plot()
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
I'm liking that **[BLOCK_POP_LOG]**, **[MEDIAN_INCOME_LOG]**, now taking on a more normal distribution. I think I'll use that moving forward. Ok final data set.
df1.df = df1.df.drop(columns=['MEDIAN_INCOME','BLOCK_POP','MEDIAN_PRICE']) df1.df_dist_plot()
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Example of how to revert value in transformed distribution back to a meaningful value
## first find the parameters used in the transformation for each transformed column df1.xfrm_params
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
After parameters found, use those to transform to a meaningful representation
boxcox_mean = df1.df['BLOCK_POP_BOXCOX'].mean() reg_mean = invert_transform(boxcox_mean, reversed_transformation='boxcox', lamb=df1.xfrm_params['BLOCK_POP_BOXCOX']['LAMBDA']) boxcox_mean, reg_mean
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW
Correlation heatmap
df1.corr_hm()
_____no_output_____
MIT
DSC 530 - Data Exploration and Analysis/Project/.ipynb_checkpoints/DataScience-checkpoint.ipynb
Hakuna-Patata/BU_MSDS_PTW