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
Using `tables_io.read`, `tables_io.write` and `tables_io.convert`These functions can be used to read and write single tables and to convert them to different formatsThe Tables can be in any of the formats that `tables_io` supports, see more on that in the notebook below.Let's have a look
# Standard imports import os import numpy as np import tables_io from tables_io.testUtils import make_test_data # make several tables and grab one tables = make_test_data() data = tables['data'] data data_np = tables_io.convert(data, tables_io.types.NUMPY_DICT) data_np data_pd = tables_io.convert(data, tables_io.types....
_____no_output_____
MIT
nb/singleTable_example.ipynb
LSSTDESC/tables_io
File IO with `tables_io`We can write tables into several different formats. These include:1. fits: Writing `astropy.table.Table` objects to FITS files (with the suffix 'fits')2. hf5: Writing `astropy.table.Table` objects to HDF5 files (with the suffix 'hf5')3. hfd5: Writing `numpy.array` objects to HDF5 files (with ...
all_fmts = list(tables_io.types.FILE_FORMAT_SUFFIXS.keys()) + [None] print(all_fmts)
_____no_output_____
MIT
nb/singleTable_example.ipynb
LSSTDESC/tables_io
Ok let's write the data to different files
for fmt in all_fmts: if fmt is None: basename = 'test_single_native' else: basename = 'test_single_out' print("Writing to %s using format %s" % (basename, fmt)) try: os.unlink('%s.%s' % (basename, fmt)) except: pass try: tables_io.write(data, basename, fmt...
_____no_output_____
MIT
nb/singleTable_example.ipynb
LSSTDESC/tables_io
Ok, now let's read things back
data_r_fits = tables_io.read("test_single_out.fits") data_r_fits data_r_hdf5 = tables_io.read("test_single_out.hdf5") data_r_hdf5 data_r_hf5 = tables_io.read("test_single_out.hf5") data_r_hf5 data_r_pq = tables_io.read("test_single_out.pq", keys=['']) data_r_pq data_r_h5 = tables_io.read("test_single_out.h5") data_r_h5...
_____no_output_____
MIT
nb/singleTable_example.ipynb
LSSTDESC/tables_io
from time_space_reductions.netcdf_gdf_setter import Base_class_space_time_netcdf_gdfclass Space_Time_Agg_over_polygons(Base_class_space_time_netcdf_gdf): def __init__(self, gdf, xarray_dataset=None, netcdf_temporal_coord_name='time', geo_series_temporal_attribute_name = 'Datetime...
gdf = make_fake_data(3) gdf.geometry = gdf.geometry.buffer(1.15) # in degrees xnetcdf = get_netcdf_example()
C:\Anaconda3\envs\Python_3.8\lib\site-packages\pyproj\crs\crs.py:53: FutureWarning: '+init=<authority>:<code>' syntax is deprecated. '<authority>:<code>' is the preferred initialization method. When making the change, be mindful of axis order changes: https://pyproj4.github.io/pyproj/stable/gotchas.html#axis-order-chan...
MIT
examples/.ipynb_checkpoints/example_Polygons_reduction-checkpoint.ipynb
PhilipeRLeal/time_space_reductions
Using the algorithm
xnetcdf['new_data'] = xnetcdf['adg_443_qaa'] * 5 - 15 Match_Upper = get_zonal_match_up(gdf=gdf, netcdf=xnetcdf, netcdf_varnames =['adg_443_qaa', 'new_data'], dict_of_windows=dict(time_window='1M'), agg_functi...
_____no_output_____
MIT
examples/.ipynb_checkpoints/example_Polygons_reduction-checkpoint.ipynb
PhilipeRLeal/time_space_reductions
import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from itertools import product import re import time from sklearn.model_selection import train_test_split from sklearn.manifold import TSNE import tensorflow as tf from tensorflow import keras
_____no_output_____
MIT
nlp/v1_scripts/supervised_UCI_adam256_save_embedding.ipynb
solislemuslab/dna-nn-theory
Read Data
!pip install PyDrive from google.colab import drive drive.mount('/content/gdrive') def convert_label(row): if row["Classes"] == 'EI': return 0 if row["Classes"] == 'IE': return 1 if row["Classes"] == 'N': return 2 data_path = '/content/gdrive/My Drive/Colab Notebooks/UCI/' splice_df = pd.read_csv(data...
Training Dataset: loss = 0.336 and acccuracy = 86.82% Validation Dataset: loss = 0.556 and acccuracy = 78.28% Test Dataset: loss = 0.508 and acccuracy = 80.25%
MIT
nlp/v1_scripts/supervised_UCI_adam256_save_embedding.ipynb
solislemuslab/dna-nn-theory
Plaid Access TokenIn this section, you will use the plaid-python api to generate the correct authentication tokens to access data in the free developer Sandbox. This mimics how you might connect to your own account or a customer account, but due to privacy issues, this homework will only require connecting to and anal...
INSTITUTION_ID = "ins_109508" client = plaid.Client(client_id=PLAID_CLIENT_ID, secret=PLAID_SBX_SECRET_KEY, public_key=PLAID_PUBLIC_KEY, environment= PLAID_ENV )
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
2. Generate a public token
generate_tkn_response = client.Sandbox.public_token.create(INSTITUTION_ID,['transactions','income', 'assets']) generate_tkn_response
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
3. Exchange the public token for an access token
exchange_tkn_response = client.Item.public_token.exchange(generate_tkn_response['public_token']) access_token = exchange_tkn_response['access_token']
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
4. Fetch Accounts
client.Accounts.get(access_token)
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
--- Account Transactions with PlaidIn this section, you will use the Plaid Python SDK to connect to the Developer Sandbox account and grab a list of transactions. You will need to complete the following steps:1. Use the access token to fetch the transactions for the last 90 days2. Print the categories for each transac...
start_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() + datetime.timedelta(-90)) end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now()) transaction_response = client.Transactions.get(access_token,start_date,end_date) pretty_print_response(transaction_response['transactions'][:1])
[ { "account_id": "dQA7rAZzR8HMMERWxxXwIl6k46WEvPfZzzk7A", "account_owner": null, "amount": 25, "authorized_date": null, "category": [ "Payment", "Credit Card" ], "category_id": "16001000", "date": "2020-07-14", "iso_cur...
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
2. Print the categories for each transaction
for transaction in transaction_response['transactions']: print(transaction['category'])
['Payment', 'Credit Card'] ['Travel', 'Taxi'] ['Transfer', 'Debit'] ['Transfer', 'Deposit'] ['Recreation', 'Gyms and Fitness Centers'] ['Travel', 'Airlines and Aviation Services'] ['Food and Drink', 'Restaurants', 'Fast Food'] ['Food and Drink', 'Restaurants', 'Coffee Shop'] ['Food and Drink', 'Restaurants'] ['Transfer...
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
3. Create a new DataFrame using the following fields from the JSON transaction data: date, name, amount, category. (For categories with more than one label, just use the first category label in the list)
transaction_df = pd.DataFrame(columns=['Date','Name','Amount','Category']) date = [] name = [] amount = [] category = [] for i in transactions: date.append(i['date']) name.append(i['name']) amount.append(i['amount']) category.append(i['category'][0]) transaction_df['Date'] = date transaction_d...
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
4. Convert the data types to the appropriate types (i.e. datetimeindex for the date and float for the amount)
transaction_df.dtypes transaction_df['Date'] = pd.to_datetime(transaction_df['Date']) transaction_df = transaction_df.set_index(['Date']) transaction_df.dtypes
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
--- Income Analysis with PlaidIn this section, you will use the Plaid Sandbox to complete the following:1. Determine the previous year's gross income and print the results2. Determine the current monthly income and print the results3. Determine the projected yearly income and print the results
income_response = client.Income.get(access_token) pretty_print_response(income_response) print(f"Last Year's income: {income_response['income']['last_year_income_before_tax']}") print(f"Current monthly income: {income_response['income']['income_streams'][0]['monthly_income']}") print(f"Projected Year's income: {income_...
Projected Year's income: 7389
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
--- Budget AnalysisIn this section, you will use the transactions DataFrame to analyze the customer's budget1. Calculate the total spending per category and print the results (Hint: groupby or count transactions per category)2. Generate a bar chart with the number of transactions for each category 3. Calculate the exp...
# YOUR CODE HERE expenses_by_category = transaction_df.groupby('Category').sum()["Amount"] expenses_by_category expenses_by_category.plot(kind = "pie", title = "Expenses by Category",subplots=True, figsize = (10,10))
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
Calculate the expenses per month
transaction_df.reset_index(inplace=True) transaction_df['month'] = pd.DatetimeIndex(transaction_df['Date']).month transaction_df.head() transactions_per_month = transaction_df.groupby('month').sum() transactions_per_month transactions_per_month.plot(kind = 'bar', title = "Transactions per Month", rot=45)
_____no_output_____
Apache-2.0
account_summary.ipynb
mostafajoma/API_Homework
Environment Checker Utils Utilities for collecting/checking `fastai` user environment
from fastai.utils import * from fastai.gen_doc.nbdoc import * from fastai.utils import * show_doc(show_install)
_____no_output_____
Apache-2.0
docs_src/utils.collect_env.ipynb
oegedijk/fastai
without nvidia-smi printout:`python -m fastai.utils.show_install`with nvidia-smi printout:`python -m fastai.utils.show_install 1` [`show_install`](/utils.collect_env.htmlshow_install)
show_doc(check_perf)
_____no_output_____
Apache-2.0
docs_src/utils.collect_env.ipynb
oegedijk/fastai
Multi-label classification
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.conv_learner import * PATH = 'data/planet/' # Data preparation steps if you are using Crestle: os.makedirs('data/planet/models', exist_ok=True) os.makedirs('/cache/planet/tmp', exist_ok=True) !ln -s /datasets/kaggle/planet-understanding-the-amazon-fr...
models/ test-jpg/ tmp/ train-jpg/ train_v2.csv*
Apache-2.0
courses/dl1/lesson2-image_models.ipynb
wpride/fastai
Multi-label versus single-label classification
from fastai.plots import * def get_1st(path): return glob(f'{path}/*.*')[0] dc_path = "data/dogscats/valid/" list_paths = [get_1st(f"{dc_path}cats"), get_1st(f"{dc_path}dogs")] plots_from_files(list_paths, titles=["cat", "dog"], maintitle="Single-label classification")
_____no_output_____
Apache-2.0
courses/dl1/lesson2-image_models.ipynb
wpride/fastai
In single-label classification each sample belongs to one class. In the previous example, each image is either a *dog* or a *cat*.
list_paths = [f"{PATH}train-jpg/train_0.jpg", f"{PATH}train-jpg/train_1.jpg"] titles=["haze primary", "agriculture clear primary water"] plots_from_files(list_paths, titles=titles, maintitle="Multi-label classification")
_____no_output_____
Apache-2.0
courses/dl1/lesson2-image_models.ipynb
wpride/fastai
In multi-label classification each sample can belong to one or more clases. In the previous example, the first images belongs to two clases: *haze* and *primary*. The second image belongs to four clases: *agriculture*, *clear*, *primary* and *water*. Multi-label models for Planet dataset
from planet import f2 metrics=[f2] f_model = resnet34 label_csv = f'{PATH}train_v2.csv' n = len(list(open(label_csv)))-1 val_idxs = get_cv_idxs(n)
_____no_output_____
Apache-2.0
courses/dl1/lesson2-image_models.ipynb
wpride/fastai
We use a different set of data augmentations for this dataset - we also allow vertical flips, since we don't expect vertical orientation of satellite images to change our classifications.
def get_data(sz): tfms = tfms_from_model(f_model, sz, aug_tfms=transforms_top_down, max_zoom=1.05) return ImageClassifierData.from_csv(PATH, 'train-jpg', label_csv, tfms=tfms, suffix='.jpg', val_idxs=val_idxs, test_name='test-jpg') data = get_data(256) x,y = next(iter(data.val_dl)) y list(zi...
_____no_output_____
Apache-2.0
courses/dl1/lesson2-image_models.ipynb
wpride/fastai
sentinelRequestsentinelRequest can be used to colocate a geodataframe (ie areas, trajectories, buoys, etc ...) with sentinel (1, but also 2 , 3 : all known by scihub) Install```conda install -c conda-forge lxml numpy geopandas shapely requests fiona matplotlib jupyter descartespip install --upgrade git+https://github...
!sentinelrequest --help
usage: sentinelrequest [-h] [--user USER] [--password PASSWORD] [--date DATE] [--wkt WKT] [--filename FILENAME] [--query QUERY] [--datatake DATATAKE] [--dateformat DATEFORMAT] [--dtime DTIME] [--cachedir CACHEDIR] [--cacherefres...
MIT
README.ipynb
agrouaze/sentinelrequest
"One shot" from command line:`% sentinelrequest --user=xxxx --password=xxxxx --date='2018-09-23 00:00' --date='2018-09-23 12:00' --filename='S1?_?W_GRD*.SAFE' --cachedir=/home1/scratch/oarcher/scihub_cache/ --wkt='POLYGON ((-10 75, -10 86, 12 86, 12 84, -10 75))'````INFO:sentinelRequest:from 2018-09-23 00:00:00 to 201...
%matplotlib inline import geopandas as gpd import datetime import matplotlib.pyplot as plt import shapely.wkt as wkt # get your own credential from https://scihub.copernicus.eu/dhus import pickle user,password = pickle.load(open("credential.pkl","rb")) import sentinelrequest as sr # set default values, so we don't h...
Help on function scihubQuery in module sentinelrequest: scihubQuery(gdf=None, startdate=None, stopdate=None, date=None, dtime=None, timedelta_slice=None, filename=None, datatake=0, duplicate=False, query=None, user=None, password=None, min_sea_percent=None, fig=None, cachedir=None, cacherefreshrecent=None, progress=Tr...
MIT
README.ipynb
agrouaze/sentinelrequest
Simplest api usageJust a startdate and a stopdate are given, with no geometry
fig = plt.figure(figsize=(10,7)) safes = sr.scihubQuery( startdate=datetime.datetime(2018,10,2), stopdate=datetime.datetime(2018,10,3), fig=fig)
WARNING:sentinelRequest:Assuming UTC date on col beginposition WARNING:sentinelRequest:Assuming UTC date on col endposition
MIT
README.ipynb
agrouaze/sentinelrequest
The result is a geodataframe with most information from scihub:
safes.iloc[0]
_____no_output_____
MIT
README.ipynb
agrouaze/sentinelrequest
Most fields are converted from str to python type (geometry, datetime, int ...)
safes.iloc[1:4]['footprint'].plot() print('safe was ingested %s after aquisition' % (safes.iloc[0]['ingestiondate']-safes.iloc[0]['endposition']))
safe was ingested 0 days 05:50:26.096000 after aquisition
MIT
README.ipynb
agrouaze/sentinelrequest
Using a geodataframe with geometries As an example, two areas are defined. Note that the index is named with the area name
gdf = gpd.GeoDataFrame({ "beginposition" : [ datetime.datetime(2018,10,2,0) , datetime.datetime(2018,10,13,0) ], "endposition" : [ datetime.datetime(2018,10,2,21) ,datetime.datetime(2018,10,13,18) ], "geometry" : [ wkt.loads("POINT (-7.5 53)").buffer(4), wkt.loads("POLYGON ((-12 35, -5...
WARNING:sentinelRequest:Assuming UTC date on col beginposition WARNING:sentinelRequest:Assuming UTC date on col endposition WARNING:sentinelRequest:no crs provided. assuming lon/lat with greenwich/antimeridian handling INFO:sentinelRequest:Slicing into 2 chunks of 7 days, 0:00:00 ... INFO:sentinelRequest:Slicing done i...
MIT
README.ipynb
agrouaze/sentinelrequest
User requested area are in green, and found safes are in blue. Index from original request are preserved, so it's easy to know the area that belong to a safe. (See end of example 2 for advanced index handling).
safes.loc['Portugal']
_____no_output_____
MIT
README.ipynb
agrouaze/sentinelrequest
Working with projectionSentinelRequest works with projections, by defining crs in gdf.The colocalisation is done using this crs.get safes around 1000km, at 84° (North pole included)
import pyproj gdf = gpd.GeoDataFrame({ "beginposition" : [ datetime.datetime(2019,12,1,0) ], "endposition" : [ datetime.datetime(2019,12,4,0)], "geometry" : [ wkt.loads("POINT (0 84)")] },index=["Artic"], crs=pyproj.CRS('epsg:4326')) # to polar projection (units in meters) gdf.t...
WARNING:sentinelRequest:Assuming UTC date on col beginposition WARNING:sentinelRequest:Assuming UTC date on col endposition
MIT
README.ipynb
agrouaze/sentinelrequest
Cyclone track colocalization
import pandas as pd #ibtracs=gpd.read_file('tmp/IBTrACS.NA.list.v04r00.points.shp') #gdf_track=ibtracs[ibtracs['SID'] == '2019235N10324'] #gdf_track=gdf_track[['ISO_TIME','USA_WIND','geometry']] #gdf_track['ISO_TIME']=pd.to_datetime(gdf_track['ISO_TIME'],format="%Y-%m-%d %H:%M:%S") #gdf_track.reset_index(inplace = True...
INFO:sentinelRequest:Slicing into 3 chunks of 7 days, 0:00:00 ... INFO:sentinelRequest:Slicing done in 0.1s . 3/3 non empty slices.
MIT
README.ipynb
agrouaze/sentinelrequest
datatakeHere, `datatake=1` is specified to retrieve adjacents safes from colocated ones (in cyan). When specified, the result contain a `datatake_index` column. 0 means the colocated one, and other values are the range of the adjacent safe (up to -n..n with `datatake=n`)Positive `datatake_index` are for safes *after* ...
safes[['filename','datatake_index']]
_____no_output_____
MIT
README.ipynb
agrouaze/sentinelrequest
Time slicing with timedelta_sliceOne can see on previous figure that 3 requests are done. gdf rows are grouped to reduce the amount of scihub requests with the `timedelta_slice` parameter (default to `datetime.timedelta(weeks=1)` )If we reduce `timedelta_slice`, we can see that more scihub request are done, with less ...
# same request as above, but with reduced timedelta_slice fig = plt.figure(figsize=(10,7)) safes = sr.scihubQuery( gdf=gdf_track, date='ISO_TIME', dtime=datetime.timedelta(hours=1.5), timedelta_slice=datetime.timedelta(days=1), datatake=1, full_fig = True, # to show inte...
INFO:sentinelRequest:Slicing into 18 chunks of 1 day, 0:00:00 ... INFO:sentinelRequest:Slicing done in 0.1s . 18/18 non empty slices.
MIT
README.ipynb
agrouaze/sentinelrequest
Merging source and result with shared indexAs seen before, the result (safes) share the same index as the source. So we can merge the two geodataframe, to associate a wind speed from the cyclone track with the safe, and compute distance from the eye to the safe.
# here, we merge the result with the source request, to associate wind speed to each safe. merged=safes[['filename','datatake_index','footprint']].merge( gdf_track[['USA_WIND','geometry']],left_index=True,right_index=True) merged['eye_dist'] = merged.set_geometry('geometry').distance(merged.set_geometry('footprint'...
<ipython-input-16-6297d856a9af>:4: UserWarning: Geometry is in a geographic CRS. Results from 'distance' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation. merged['eye_dist'] = merged.set_geometry('geometry').distance(merged.set_geometry('footprint').ext...
MIT
README.ipynb
agrouaze/sentinelrequest
Annexes Antimeridian handling: small geometry vs large oneGiven 2 points on the earth, there is two possible paths: one short, and one long that wrap around the earth.Note: only longitude is wrapped, as if earth was a cylinder (epgs 4326 used for computation) By default, geometry are the smallest ones. To preserve a ...
from shapely.geometry import GeometryCollection # the polygon is more than 180 deg wide. It will be wrapped, and will cross antimeridian large_poly = wkt.loads("POLYGON ((-140 -14, 140 -14, 140 -20, -140 -20, -140 -14))") gdf = gpd.GeoDataFrame({ "beginposition" : [ datetime.datetime(2018,10,1)], "end...
_____no_output_____
MIT
README.ipynb
agrouaze/sentinelrequest
Reproduct Autopilot ArchitectureThe Autopilot has the following Architecture:~ ResNet50-like backbone~ FPN - DeepLabV3- UNet - like heads~ 15 tasks ~ subtasks i.e. if task is car detection, then the sub task is what kind of car, is it stationary? Parked, broken down?For later exploration:Stitching up of images acro...
import torch import torch.nn as nn import torch.optim as optim import torchvision from torchvision import models, transforms import matplotlib.pyplot as plt import numpy as np batch_size = 50 # get the CIFAR-10 images: train_data_transform = transforms.Compose([ transforms.Resize(224), transforms.RandomHorizo...
Files already downloaded and verified
MIT
Autopilot/Autopilot_replicated.ipynb
Hira63S/DeepLearningResearch
CIFAR10 Data10000 x 3072 numpy arrays. i.e 1024 values i.e. 32x32 image and since there are 3 channels, we get 3072 shaped numpy arrays.Each row in the array stores a 32x32 colour imageThe first 1024 entries contain the red channel values, the next 1024 are green and the next 1024 are blue.
def imshow(img): img = img/2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1,2,0))) plt.show() dataiter = iter(train_loader) images, labels = dataiter.next() classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') imshow(torchv...
_____no_output_____
MIT
Autopilot/Autopilot_replicated.ipynb
Hira63S/DeepLearningResearch
Now, onto the transfer learning scenario where we are going to use the pretrained network as a feature extractor.1. Let's use ResNet502. Replace last layer of the model with a new layer with 10 outputs3. Exclude the existing network layers from the backward pass and only pass the newly added fully-connected layer to th...
model = torchvision.models.resnet50(pretrained=True) model.eval() def train(model, criterion, optimizer, train_loader, valid_loader, save_file_name, max_epochs_stop=3, n_epochs = 20, print_every=2): """Train the Pytorch model while including the ...
_____no_output_____
MIT
Autopilot/Autopilot_replicated.ipynb
Hira63S/DeepLearningResearch
model.classifier[6] = nn.Sequential( nn.Linear(n_inputs, 256), nn.ReLU(), nn.Dropout(0.4), nn.Linear(256, n_classes), nn.LogSoftmax(dim=1))
tl_feature_extractor()
Epoch 1/5
MIT
Autopilot/Autopilot_replicated.ipynb
Hira63S/DeepLearningResearch
from google.colab import auth auth.authenticate_user() from google.colab import drive drive.mount('/content/drive')
Mounted at /content/drive
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
E-commerce Dataset 2020**For this project, we want to enhance the webpage with the provided dataset of e-Commerce dataset in February and April by taking in consideration COVID-19 pandemic.**Goal: Our goal is analyzing customer online purchasing behavior during pre covid-19 and post covid-19 using February and April da...
%%bigquery --project ba775-team-4b SELECT brand, count(brand) AS total_brand_purchase FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` WHERE event_type = 'purchase' GROUP BY brand ORDER BY count(brand) DESC LIMIT 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: We noticed that Samsung is consumer’s favorite brand, followed by Apple and Xiaomi. All electronic brands! Next, let’s give a look to the conversion rate for the month of February from 2020.
%%bigquery --project ba775-team-4b SELECT COUNTIF(event_type = 'purchase')/COUNT(event_type) AS conversion_rate, category_code, ROUND(sum(price), 2) AS total_Price FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` GROUP BY category_code ORDER BY Conversion_rate DESC limit 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: It shows that the highest conversion rate is the construction tools with a rate of 0.0397, followed by apparel with a rate of 0.0334. We also want to identify who are the Top consumers in the ecommerce webpage, and how much do they spend for this month, February.
%%bigquery --project ba775-team-4b SELECT user_id, ROUND(SUM(price)) AS total_spending_FEB FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` WHERE event_type = 'purchase' GROUP BY user_id ORDER BY total_spending_FEB DESC LIMIT 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Result: our Top consumer identified as user_id: '563051763' spent around $302,726.0 on the webpage. Now, let’s check the average of all users’ spendings for the month of February.
%%bigquery --project ba775-team-4b SELECT ROUND(AVG(price), 2) as avg_spending_feb FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` WHERE event_type = 'purchase' LIMIT 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Result: The average of users’ spendings for the month of February is $317.57. After identifying the highest consumer as user_id: '563051763', we want to compare their spending with the average of all users’ spendings for the month of February.
%%bigquery --project ba775-team-4b SELECT user_id AS USER_ID, ROUND(SUM(price)) AS Total_spending, COUNT(user_session) as Sessions, ( SELECT round(AVG(price), 2) as avg_spending FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` WHERE event_type = 'purchase' ) as Avg_spending_of_all_users FROM `ba775-team-4b.4b_da...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
This query shows the top buyer who have spend the most in this ecommerce website, number of sessions, and the average of all users' spendings. Now, we would check for the month of April (post-COVID): For the month of April, 2020. We will identify the Top 10 popular brands that were purchased by the consumers during po...
%%bigquery --project ba775-team-4b SELECT brand, count(brand) AS total_brand_purchase FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE event_type = 'purchase' GROUP BY brand ORDER BY count(brand) DESC LIMIT 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: We noticed that the results are the same as pre-COVID (February). Samsung is still consumer’s favorite brand, followed by Apple and Xiaomi. All electronic brands! Let’s give a look to the conversion rate for the month of April.
%%bigquery --project ba775-team-4b SELECT countif(event_type = 'purchase')/count(event_type) AS Conversion_rate, category_code, sum(price) Total_Price FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` GROUP BY category_code ORDER BY Conversion_rate DESC limit 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: It shows that the highest conversion rate is the stationery paper with a rate of 0.038, followed by kitchen appliances with a small difference of 0.001. Next, we want to identify who are the Top consumers in the ecommerce webpage, and how much they spend.
%%bigquery --project ba775-team-4b SELECT user_id, round(SUM(price), 2) as total_spending FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE event_type = 'purchase' GROUP BY user_id ORDER by total_spending DESC LIMIT 10
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: our Top consumer identified as user_id: '553446649' spent around $122,525.19 on the webpage, which is way more lower than in February. This leads to a better understanding of consumers' behaviour that due the pandemic consumers had shifted their values, and cutting down unneed purchases to essentials. Now, let...
%%bigquery --project ba775-team-4b SELECT ROUND(AVG(price), 2) as avg_spending_of_all_users FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE event_type = 'purchase'
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Result: As we expected, the average of users’ spendings also decreased during pandemic. Average for April is `$252.93`, while for Feb was `$317.57`. After identifying the highest consumer as user_id: '553446649', we want to compare their spending with the average of all users’ spendings for the month of April.
%%bigquery --project ba775-team-4b SELECT user_id AS USER_ID, ROUND(SUM(price)) AS TOTAL_SPENDING,COUNT(user_session) AS TOTA_SESSIONS, ( SELECT round(AVG(price), 2) as avg_spending FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE event_type = 'purchase' ) as AVG_SPENDING_OF_ALL_USERS FROM `ba775-team-4...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
This query shows the top buyer who have spend the most in this ecommerce website, and the average of all users' spendings Let's check deeper the insights by combining both datasets! We also want to know how many times they shop on this website in February and April.
%%bigquery --project ba775-team-4b SELECT user_id, COUNT(user_id) AS returning FROM ( SELECT user_id, event_type FROM `ba775-team-4b.4b_dataset.ecommerce_feb_2020` AS FEB UNION ALL SELECT user_id, event_type FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` AS APR ) WHERE event_type = 'purchase' GROUP BY user_id HA...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: Our top consumer identified as user_id: ‘609817194’ returned back to the website 573 times. Surprisingly, our top consumer from the month of February and April are not in the Top 10. Now we want to see the impact of COVID-19 by finding the percentage change in sales for popular categories in February
%%bigquery --project ba775-team-4b SELECT category_code, (total_sales_apr - total_sales_feb)/total_sales_feb AS percent_change FROM ( SELECT * FROM (SELECT category_code, SUM(price) AS total_sales_apr FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE category_code IS NOT NULL AND event_type = 'purchase'...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Results: Most popular categories have lower sales in April than in February. But headphone, massager and refrigerators categories have higher sales in April. It might casued by working from home. Are views correlated with the number of speding in each month?
%%bigquery --project ba775-team-4b select count(event_type) as feb_visits, (select round(sum(price),2) as profit_from_feb from `ba775-team-4b.4b_dataset.ecommerce_feb_2020` where event_type = 'purchase')feb_profit, (select count(event_type) as total_visits_april FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` w...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
There is a negative correlation between the number of views and consumer's spending on each month.Results: April visits times increased by 9.8% since February, but decreased sales by 21.84%. Also, we wants to investigate how well samsung's top selling categories in February performed in April
%%bigquery --project ba775-team-4b SELECT A.*,FEB_total_sales,round(APR_total_sales-FEB_total_sales,2) FEB_APR_SalesDifferences, round(((APR_total_sales-FEB_total_sales)/FEB_total_sales),2) FEB_APR_SalesChanges_percentage FROM (SELECT A.*,B.APR_total_sales FROM (SELECT A.brand,A.category_code,count(A.brand) AS coun...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Result: most of the February's top-selling categories for samsung increased a lot in April, especially for air conditioner category. Number of products they purchased in different category.
%%bigquery --project ba775-team-4b SELECT user_id,num_of_accessories,num_of_apparel,num_of_appliances,num_of_auto,num_of_computers,num_of_construction,num_of_country_yard,num_of_electronics,num_of_furniture,num_of_kids,num_of_medicine,num_of_sport,num_of_stationery from (SELECT user_id, count(user_id) as num_of_accesso...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Abandon Rate
%%bigquery --project ba775-team-4b SELECT a.user_id, a.cart_count, ifnull(b.purchase_count,0) as purchase_count, round((ifnull(b.purchase_count,0)/a.cart_count),3)as purchase_rate, round((1-(ifnull(b.purchase_count,0)/a.cart_count)),3) as abandon_rate FROM `ba775-team-4b.4b_dataset.cart_count_per_user_id` a left j...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
The abandon rate can be used as the metric to evaluate the purchase power of the users. The abandon rate of a certain user = 1-(number of 'purchase' event /number of 'cart' event). Only the user info with high abandon rate(>0.9) is included and have the potential to work on increasing sales conversion, such as sending ...
# Using product features CREATE MODEL model.products OPTIONS ( model_type = 'kmeans', num_clusters = 2, distance_type = 'euclidean') AS SELECT category_code, brand, price, count(product_id) FROM `ba775-team-4b.4b_dataset.ecommerce_april_2020` WHERE event_type='purchase' GROUP BY category_code, product_id, ...
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
Tableau Dashboard https://prod-useast-a.online.tableau.com/t/soltaniehha/views/BA775Team4bProject_16040742108920/EcommerceDashboard?:origin=card_share_link&:embed=n
from IPython.display import Image # Top Purchase Brand of Feberary and April Image(filename='Top Brand.png') # Abandon Rate of Feberary and April Image(filename='Abandon Rate.png')
_____no_output_____
MIT
BA_775_Team_Assignment_Team_4b.ipynb
Amberineee/ecommerce_covid_analysis
define functions
read_FM <- function(filename){ df_FM = data.frame(readRDS(filename),stringsAsFactors=FALSE,check.names=FALSE) rownames(df_FM) <- make.names(rownames(df_FM), unique=TRUE) df_FM[is.na(df_FM)] <- 0 return(df_FM) } run_pca <- function(mat,num_pcs=50,remove_first_PC=FALSE,scale=FALSE,center=FALSE){ set....
_____no_output_____
MIT
Extra/Cusanovich_2018_subset/test_blacklist/run_umap_cusanovich2018subset_no_blacklist_filtering.ipynb
tAndreani/scATAC-benchmarking
Input
workdir = '../output/' path_umap = paste0(workdir,'umap_rds/') system(paste0('mkdir -p ',path_umap)) path_fm = paste0(workdir,'feature_matrices/') metadata <- read.table('../input/metadata.tsv', header = TRUE, stringsAsFactors=FALSE,quote="",row.names=1) list.files(pa...
_____no_output_____
MIT
Extra/Cusanovich_2018_subset/test_blacklist/run_umap_cusanovich2018subset_no_blacklist_filtering.ipynb
tAndreani/scATAC-benchmarking
SnapATAC
df_umap_SnapATAC <- run_umap(fm_SnapATAC) head(df_umap_SnapATAC) p_SnapATAC <- plot_umap(df_umap_SnapATAC,labels = labels,colormap = colormap,title='SnapATAC') p_SnapATAC
_____no_output_____
MIT
Extra/Cusanovich_2018_subset/test_blacklist/run_umap_cusanovich2018subset_no_blacklist_filtering.ipynb
tAndreani/scATAC-benchmarking
SCRAT
df_umap_SCRAT <- run_umap(fm_SCRAT) p_SCRAT <- plot_umap(df_umap_SCRAT,labels = labels,colormap = colormap,title='SCRAT') p_SCRAT
_____no_output_____
MIT
Extra/Cusanovich_2018_subset/test_blacklist/run_umap_cusanovich2018subset_no_blacklist_filtering.ipynb
tAndreani/scATAC-benchmarking
Save feature matrices and UMAP coordinates
dataset = 'cusanovich2018subset_no_blacklist_filtering' saveRDS(df_umap_SnapATAC,paste0(path_umap,'df_umap_SnapATAC.rds')) saveRDS(df_umap_SCRAT,paste0(path_umap,'df_umap_SCRAT.rds')) save.image(file = 'run_umap_cusanovich2018subset_no_blacklist_filtering.RData') fig_width = 8 fig_height = 4 options(repr.plot.width=fi...
_____no_output_____
MIT
Extra/Cusanovich_2018_subset/test_blacklist/run_umap_cusanovich2018subset_no_blacklist_filtering.ipynb
tAndreani/scATAC-benchmarking
Learner> This contains fastai Learner extensions.
#export from tsai.imports import * from tsai.data.core import * from tsai.data.validation import * from tsai.models.all import * from tsai.models.InceptionTimePlus import * from fastai.learner import * from fastai.vision.models.all import * from fastai.data.transforms import * #export @patch def show_batch(self:Learne...
_____no_output_____
Apache-2.0
nbs/052_learner.ipynb
clancy0614/tsai
"Price Charts with Technical Indicators"> "Calculating Stock Price Indicators using FINTA python library, and visualizing using plotly python library."- toc: false- branch: master- badges: true- comments: true- author: Ijeoma Odoko- categories: [stocks, python, finta, pandas, plotly, ipywidgets] ![markus-spiske-69ppqH...
!pip install finta
Requirement already satisfied: finta in /usr/local/lib/python3.6/dist-packages (1.2) Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from finta) (1.18.5) Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from finta) (1.1.2) Requirement already satisfied: py...
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Load required libraries
from pandas_datareader import data import numpy as np from datetime import datetime from datetime import date, timedelta import pandas as pd # import ipwidgets library and functions from __future__ import print_function from ipywidgets import interact, interactive, fixed import ipywidgets as widgets from IPython.disp...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Create widgets and dataframe for the stock data*Instructions for use. *1. Insert tuple of stock list. 2. Select stock from dropdown. 3. Select number of calendar days for dates from the last trading day. 4. Rerun all code after.
# Insert a tuple of unique tickers into the options variables. #tickers = ('MMM', 'AOS', 'AAN', 'ABB', 'ABT', 'ABBV', 'ABM', 'ACN', 'AYI', 'GOLF', 'ADCT', 'ADT', 'AAP', 'ADSW', 'WMS', 'ACM', 'AEG', 'AER', 'AJRD', 'AMG', 'AFL', 'AGCO', 'A', 'AEM', 'ADC', 'AL', 'APD', 'AGI', 'ALK', 'ALB', 'ACI', 'AA', 'ALC', 'ARE', 'AQN'...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Download data for the stock
# create text to show stock ticker v = widgets.Text( value=stock_ticker.value, description='Stockticker:', disabled=True ) # create function to load stock data from yahoo def load_stock_data(stock_ticker, w): start = date.today() - timedelta(w) today = date.today() stock_data = data.DataRead...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Calculate some Stock Price Indicators
# create example dataframe to try out the functions ex_df = ohlcv.copy() ex_df['RSI'] = TA.RSI(ex_df) ex_df['Simple_Moving_Average_50'] = TA.SMA(ex_df, 50) ex_df[['macd', 'macd_s']] = TA.MACD(ex_df) ex_df
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Create a function to create a dataframe that captures some stock technical indicators
# create function to create the Stock Indicator dataframe def create_dataframe(df): """ This function creates a Dataframe for key indicators """ df['Daily_Returns'] = df['close'].pct_change() # create column for daily returns df['Price_Up_or_Down'] = np.where(df['Daily_Returns'] < 0, -1...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
VISUALIZATIONS USING PLOTLY Price Action Chart
# create OHLC charts with Plotly import plotly.graph_objects as go fig_ohlc = go.Figure(data=[go.Ohlc(x=stocks_df.index, open=stocks_df['open'], high=stocks_df['high'], low=stocks_df['low'], close=stocks_df['close'], showlegend=False)]) fig_ohl...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Momentum Indicators
#hide import plotly.graph_objects as go import plotly.offline as pyo trace1 = go.Scatter(x=stocks_df.index, y=stocks_df['macd'], mode='lines', marker=dict(color="green"), showlegend=True, name='macd') trace2 = go.Scatter(x=stocks_df.index, y=stocks_df['macd_signal'], mode='lines', marker=dict(color="blue"), showlegen...
_____no_output_____
Apache-2.0
_notebooks/2020-10-23-Stock_Price_Indicators_using_the_python_FINTA_library.ipynb
IjeomaOdoko/my-blog
Analyzing Hamlet
%load_ext autoreload %autoreload 2 import src.data import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os from collections import OrderedDict from IPython.display import display pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 pd.set_option("displa...
_____no_output_____
MIT
notebooks/01.4_data_inventory.ipynb
martinlarsalbert/datadriven-energieffektivisering-av-fartyg
Train mnist with Tensorflow**Requirements** - In order to benefit from this tutorial, you will need:- A basic understanding of Machine Learning- An Azure account with an active subscription - [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F)- An Azure ML workspace with computer cluster...
# import required libraries from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential from azure.ai.ml import MLClient from azure.ai.ml.dsl import pipeline from azure.ai.ml.entities import ResourceConfiguration
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
1.2 Configure credentialWe are using `DefaultAzureCredential` to get access to workspace. `DefaultAzureCredential` should be capable of handling most Azure SDK authentication scenarios. Reference for more available credentials if it does not work for you: [configure credential example](../../configuration.ipynb), [azu...
try: credential = DefaultAzureCredential() # Check if given credential can get token successfully. credential.get_token("https://management.azure.com/.default") except Exception as ex: # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential not work credential = InteractiveBrowser...
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
1.3 Get a handle to the workspaceWe use config file to connect to a workspace. The Azure ML workspace should be configured with computer cluster. [Check this notebook for configure a workspace](../../configuration.ipynb)
# Get a handle to workspace ml_client = MLClient.from_config(credential=credential) # Retrieve an already attached Azure Machine Learning Compute. cluster_name = "cpu-cluster" print(ml_client.compute.get(cluster_name))
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
2. Define command componentWe defined sample component using `command_component` decorator in [component.py](src/component.py).
with open("src/component.py") as fin: print(fin.read()) %load_ext autoreload %autoreload 2 from src.component import train_tf help(train_tf)
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
3. Pipeline job 3.1 Build pipeline
@pipeline() def train_mnist_with_tensorflow(): """Train using TF component.""" tf_job = train_tf(epochs=1) tf_job.compute = "cpu-cluster" tf_job.resources = ResourceConfiguration(instance_count=2) tf_job.distribution.worker_count = 2 tf_job.outputs.trained_model_output.mode = "upload" # create...
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
3.2 Submit pipeline job
# submit job to workspace pipeline_job = ml_client.jobs.create_or_update( pipeline_job, experiment_name="pipeline_samples" ) pipeline_job # Wait until the job completes ml_client.jobs.stream(pipeline_job.name)
_____no_output_____
MIT
sdk/jobs/pipelines/2a_train_mnist_with_tensorflow/train_mnist_with_tensorflow.ipynb
jplummer01/azureml-examples
import json import datetime input_dir = './' output_dir = './' filename = 'name' data = {} # Save ts = datetime.datetime.utcnow().strftime('%y-%m-%dT%H-%M-%S') # so you don't overwrite, and save timestamp with open(output_dir+f'{filename}_{ts}.json', "w") as fp: json.dump(data, fp, indent=4) # Load with o...
_____no_output_____
Apache-2.0
load_write_json.ipynb
danielmlow/tutorials
Loading the model, uncertainities, and outcomes and generate experiments
# Here we only generate experiments for loading the necessary components. #The actual results will be loaded in the next cell. # Open Excel input data from the notebook directory before runnign the code in multi-processing. # Close the folder where the results will be saved in multi-processing. # This line must be at...
[MainProcess/INFO] results saved successfully to D:\moallemie\EM_analysis\Data\SDG_experiments_ranking_verification_GWP per Capita Indicator_sc500.tar.gz
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_GWP per Capita Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
Calculating SA (Morris) metrics
# Morris mu_star index calculation as a function of number of scenarios and time def make_morris_df(scores, problem, outcome_var, sc, t): scores_filtered = {k:scores[k] for k in ['mu_star','mu_star_conf','mu','sigma']} Si_df = pd.DataFrame(scores_filtered, index=problem['names']) indices = Si_df[['mu...
_____no_output_____
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_GWP per Capita Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
Where to draw the line between important and not important?
''' Modifed from Waterprogramming blog by Antonia Hadgimichael: https://github.com/antonia-had/SA_verification The idea is that we create 2 additiopnal Sets (current SA samples are Set 1). We can create a Set 2, using only the T most important factors from our Set 1 sample, and fixing all other factors to their defa...
[MainProcess/INFO] pool started [MainProcess/INFO] performing 10500 scenarios * 1 policies * 1 model(s) = 10500 experiments [MainProcess/INFO] 1050 cases completed [MainProcess/INFO] 2100 cases completed [MainProcess/INFO] 3150 cases completed [MainProcess/INFO] 4200 cases completed [MainProcess/INFO] 5250 cases comple...
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_GWP per Capita Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
Imports
import numpy as np import pandas as pd import os import time from itertools import permutations, combinations from IPython.display import display
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Prompts to choose which store you want
print("Welcome to Apriori 2.0!") store_num = input("Please select your store \n 1. Amazon \n 2. Nike \n 3. Best Buy \n 4. K-Mart \n 5. Walmart\n") print(store_num) support_percent = input("Please enter the percentage of Support you want?\n") print(support_percent) confidence_percent = input("Please enter the percentage...
Welcome to Apriori 2.0! Please select your store 1. Amazon 2. Nike 3. Best Buy 4. K-Mart 5. Walmart 1 1 Please enter the percentage of Support you want? 40 40 Please enter the percentage of Confidence you want? 40 40
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
These are my dictionaries to choose which store to get based in Key-Value Pairs
def number_to_store(store_number): switcher = { 1: "data/amazon_transactions.csv", 2: "data/nike_transaction.csv", 3: "data/best_buy_transaction.csv", 4: "data/k_mart_transaction.csv", 5: "data/walmart_transaction.csv" } return switcher.get(store_number) def number_...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
We first have to read in the csv files and make sure that the inputs received from the user are valid
def a_priori_read(item_list, transaction, support_percentage, confidence_percentage): # Create two different functions one that is solo for read in the file data and the other that is algorithmic with the data if support_percentage > 100 or confidence_percentage > 100 or support_percentage < 0 or confidence_per...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
The first go around of the Apriori Algorithm we find the items that are most frequent when K=1 This is so that we can find the most frequent items given the transactions
def ap_1(items_names, trans, support_percentage, confidence_percentage, k_value): counter = np.zeros(len(items_names), dtype=int) for i in trans: i = list((map(str.strip, i.split(',')))) s1 = set(i) nums = 0 for x in items_names: s2 = set() s2.add(x) ...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Then we use this function below to find item sets that are most frequent when K > 1
def ap_2(item_comb, k_value, trans, support_percentage): boo = True comb = combinations(item_comb, k_value) comb = list(comb) counter = np.zeros(len(comb), dtype=int) if k_value > 1: for i in trans: i = list((map(str.strip, i.split(',')))) s1 = set(i) nums...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Calls of functions and variable saving
frames = [] items_names, trans, support_percent, confidence_percent, k_value = a_priori_read( str(number_to_item_list_of_store(int(store_num))), str(number_to_store(int(store_num))), int(support_percent), int(confidence_percent)) items, supp, k_value, df = ap_1(items_names, trans, support_percent, confidence_p...
transaction_id \ 0 1 1 2 2 3 3 4 4 5 transaction 0 A Beginner’s Guide, Java: The Complete Reference...
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Increasing K by 1 until we can longer support the support value
while boo: df_1, boo = ap_2(items, k_value, trans, support_percent) frames.append(df_1) k_value += 1
When K = 2 item_name support k_val 0 (A Beginner’s Guide, Java: The Complete Reference) 45 2 1 (A Beginner’s Guide, Java For Dummies) 45 2 4 (Java: The Complete Reference, Java For Dummies) 50 ...
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Combine the dataframes we have from when we increase K
print("results of item-sets that meet support are below") display(pd.concat(frames)) df_supp = pd.concat(frames) # df_supp.head()
results of item-sets that meet support are below
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Reset the index just to organize it and the results after we find the most frequent sets in the list of transactions
df_supp = df_supp.reset_index().drop('index',axis=1) df_supp
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
This is the FUNCTION that genrerates the Associations (Permutations) and calculating the Confidence of the item sets
def confidence(val): #Since we already have our support for our items what we need to worry about is the confidence levels #item_set before the arrow df_before = df_supp.loc[df_supp['k_val'] == val] stuff_name_before = np.array(df_before["item_name"]) support_arr_before = np.array(df_befo...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
Finding the max k value in the given set
try: max(df_supp["k_val"]) except: print("No max was found...")
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch
This is where I iteratively call the confidence() function
df_frames = [] try: if len(df_supp["k_val"]) != 0 : for lp in range(1,max(df_supp["k_val"])+1): #print(lp) df_0 = confidence(lp) df_0 = df_0[df_0.support_sing != 0] df_frames.append(df_0) df_associations = pd.concat(df_frames) display(df_assoc...
_____no_output_____
MIT
.ipynb_checkpoints/Apriori_Algo-checkpoint.ipynb
MichaelWoo-git/Apriori_Algorithm_from_Scratch