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
Options Load data
filename = '../data/data_sample_monthly.csv' infile = filename df_comb_long = pd.read_csv(infile) df_comb_long['date'] = pd.to_datetime(df_comb_long['date']) #df_comb_long.head() #eq_name = 'Equity Parent' eq_name = 'company' df_prices = df_comb_long.pivot(values='stock_price', index='date', columns=eq_name) # monthl...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Create base indices
df_market_cap = df_comb_long.pivot(values='MarketCap_Mlns', index='date', columns=eq_name) df_market_cap.index = df_market_cap.index.map(project_to_first) # deal with the missing values by taking the previously available one df_market_cap.ffill(inplace=True) # set to zero when not available, this takes care of the ma...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Market cap weighted
total_market_cap = df_market_cap.sum(axis=1) # weights determined in the same month as market cap df_weights = df_market_cap.div(total_market_cap, axis=0) # the weights for the index should be determined by past information, # i.e.by previous month market_cap #df_weights_mc = df_weights.shift(1).bfill() df_weights_mc ...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Equal weights
df_temp = (df_weights_mc > 0.0).astype(int) df_weights_equal = df_temp.div(df_temp.sum(axis=1), axis=0)
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
compute index returns
df_mc_index_returns = pd.DataFrame((df_returns * df_weights_mc).sum(axis=1),columns=['mc_return']) df_mc_index_returns.dropna(inplace=True) df_equal_index_returns = pd.DataFrame((df_returns * df_weights_equal).sum(axis=1),columns=['equal_return']) df_equal_index_returns.dropna(inplace=True)
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Index based on model predictionsBase indices * market cap weighted * equal weighted Weight generation
l_base_weights = ['Market Cap', 'Equal'] l_weighting_schemes = ['0'] # Cartesian product tuples l_weights = list(itertools.product(*[l_base_weights,l_weighting_schemes])) # WEIGHT ADJUSTMENTS OPTIONS d_weights = {} #execution loop for base_mod, scheme in l_weights: print(base_mod, scheme) if base_mod == 'M...
Market Cap 0 Equal 0
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Build your strategy
# do something better than random df_rand = pd.DataFrame(np.random.uniform(low=0.0, high=0.01, size=(len(df_weights_mc.index), len(df_weights_mc.columns))), columns=list(df_weights_mc.columns), index=df_weights_mc.index) df_w = df_weights_mc + df_rand df_w = df_w.div(df_w.sum(axis=1), axis=0) d...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
Build index Monthly index levels
# build date frame with indices (no rebalancing) start_date = datetime.datetime(2009,1,1) end_date = datetime.datetime(2015,12,31) starting_level = 100 df_r_in = df_restrict_dates(df_returns, start_date, end_date) frequency = 'monthly' for k, name in enumerate(sorted(d_weights.keys())): print(name) df_...
_____no_output_____
MIT
notebooks/index_generation_odsc.ipynb
jbauer44/factor_investing
SegmentationImage segmentation is another early as well as an important image processing task. Segmentation is the process of breaking an image into groups, based on similarities of the pixels. Pixels can be similar to each other in multiple ways like brightness, color, or texture. The segmentation algorithms are to fi...
import os, sys sys.path = [os.path.abspath("../../")] + sys.path from perception4e import * from notebook4e import * import matplotlib.pyplot as plt
Using TensorFlow backend.
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
Let's take a look at it:
plt.imshow(gray_scale_image, cmap='gray', vmin=0, vmax=255) plt.axis('off') plt.show()
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
You can also generate your own grayscale images by calling `gen_gray_scale_picture` and pass the image size and grayscale levels needed:
gray_img = gen_gray_scale_picture(100, 5) plt.imshow(gray_img, cmap='gray', vmin=0, vmax=255) plt.axis('off') plt.show()
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
Now let's generate the discs we are going to use as sampling masks to tell the intensity difference between two half of the care area of an image. We can generate the discs of size 100 pixels and show them:
discs = gen_discs(100, 1) fig=plt.figure(figsize=(10, 10)) for i in range(8): img = discs[0][i] fig.add_subplot(1, 8, i+1) plt.axis('off') plt.imshow(img, cmap='gray', vmin=0, vmax=255) plt.show()
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
The white part of disc images is of value 1 while dark places are of value 0. Thus convolving the half-disc image with the corresponding area of an image will yield only half of its content. Of course, discs of size 100 is too large for an image of the same size. We will use discs of size 10 and pass them to the detect...
discs = gen_discs(10, 1) contours = probability_contour_detection(gray_img, discs[0]) show_edges(contours)
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
As we are using discs of size 10 and some boundary conditions are not dealt with in our naive algorithm, the extracted contour has a bold edge with missings near the image border. But the main structures of contours are extracted correctly which shows the ability of this algorithm. Group Contour DetectionThe alternati...
contours = group_contour_detection(gray_scale_image, 3)
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
Now let's show the extracted contours:
show_edges(contours)
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
It is not obvious as our generated image already has very clear boundaries. Let's apply the algorithm on the stapler example to see whether it will be more obvious:
import numpy as np import matplotlib.image as mpimg stapler_img = mpimg.imread('images/stapler.png', format="gray") contours = group_contour_detection(stapler_img, 5) plt.axis('off') plt.imshow(contours, cmap="gray")
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
The segmentation is very rough when using only 5 clusters. Adding to the cluster number will increase the degree of subtle of each group thus the whole picture will be more alike the original one:
contours = group_contour_detection(stapler_img, 15) plt.axis('off') plt.imshow(contours, cmap="gray")
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
Minimum Cut SegmentationAnother way to do clustering is by applying the minimum cut algorithm in graph theory. Roughly speaking, the criterion for partitioning the graph is to minimize the sum of weights of connections across the groups and maximize the sum of weights of connections within the groups. ImplementationTh...
image = gen_gray_scale_picture(size=10, level=2) show_edges(image) graph = Graph(image) graph.min_cut((0,0), (9,9))
_____no_output_____
MIT
notebooks/chapter24/Image Segmentation.ipynb
mbalduccini/aima-python
Decision TreesEstimated time needed: **15** minutes ObjectivesAfter completing this lab you will be able to:* Develop a classification model using Decision Tree Algorithm In this lab exercise, you will learn a popular machine learning algorithm, Decision Trees. You will use this classification algorithm to build...
import numpy as np import pandas as pd from sklearn.tree import DecisionTreeClassifier
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
About the dataset Imagine that you are a medical researcher compiling data for a study. You have collected data about a set of patients, all of whom suffered from the same illness. During their course of treatment, each patient responded to one of 5 medications, Drug A, Drug B, Drug c, Drug x and y. ...
!wget -O drug200.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/drug200.csv
--2021-06-06 16:57:39-- https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/drug200.csv Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.63.118.10...
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
**Did you know?** When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) Now, read the data u...
my_data = pd.read_csv("drug200.csv", delimiter=",") my_data[0:5]
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Practice What is the size of data?
# write your code here my_data.shape
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Click here for the solution```pythonmy_data.shape``` Pre-processing Using my_data as the Drug.csv data read by pandas, declare the following variables: X as the Feature Matrix (data of my_data) y as the response vector (target) Remove the column containing the target name since it doesn't contain...
X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values X[0:5]
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
As you may figure out, some features in this dataset are categorical, such as **Sex** or **BP**. Unfortunately, Sklearn Decision Trees does not handle categorical variables. We can still convert these features to numerical values using **pandas.get_dummies()**to convert the categorical variable into dummy/indicator var...
from sklearn import preprocessing le_sex = preprocessing.LabelEncoder() le_sex.fit(['F','M']) X[:,1] = le_sex.transform(X[:,1]) le_BP = preprocessing.LabelEncoder() le_BP.fit([ 'LOW', 'NORMAL', 'HIGH']) X[:,2] = le_BP.transform(X[:,2]) le_Chol = preprocessing.LabelEncoder() le_Chol.fit([ 'NORMAL', 'HIGH']) X[:,3] ...
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Now we can fill the target variable.
y = my_data["Drug"] y[0:5]
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Setting up the Decision Tree We will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.
from sklearn.model_selection import train_test_split
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Now train_test_split will return 4 different parameters. We will name them:X_trainset, X_testset, y_trainset, y_testset The train_test_split will need the parameters: X, y, test_size=0.3, and random_state=3. The X and y are the arrays required before the split, the test_size represents the ratio of the testing da...
X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
PracticePrint the shape of X_trainset and y_trainset. Ensure that the dimensions match.
# your code X_trainset.shape y_trainset.shape
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Click here for the solution```pythonprint('Shape of X training set {}'.format(X_trainset.shape),'&',' Size of Y training set {}'.format(y_trainset.shape))``` Print the shape of X_testset and y_testset. Ensure that the dimensions match.
# your code X_testset.shape
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Click here for the solution```pythonprint('Shape of X training set {}'.format(X_testset.shape),'&',' Size of Y training set {}'.format(y_testset.shape))```
y_testset.shape
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Modeling We will first create an instance of the DecisionTreeClassifier called drugTree. Inside of the classifier, specify criterion="entropy" so we can see the information gain of each node.
drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 4) drugTree # it shows the default parameters
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Next, we will fit the data with the training feature matrix X_trainset and training response vector y_trainset
drugTree.fit(X_trainset,y_trainset)
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Prediction Let's make some predictions on the testing dataset and store it into a variable called predTree.
predTree = drugTree.predict(X_testset)
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
You can print out predTree and y_testset if you want to visually compare the predictions to the actual values.
print (predTree [0:5]) print (y_testset [0:5])
['drugY' 'drugX' 'drugX' 'drugX' 'drugX'] 40 drugY 51 drugX 139 drugX 197 drugX 170 drugX Name: Drug, dtype: object
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Evaluation Next, let's import metrics from sklearn and check the accuracy of our model.
from sklearn import metrics import matplotlib.pyplot as plt print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))
DecisionTrees's Accuracy: 0.9833333333333333
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
**Accuracy classification score** computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true.In multilabel classification, the function returns the subset accuracy. If the entire set of predicted labels for a sample strictly match with the true set of...
_____no_output_____
Apache-2.0
-Decision-Trees-drug.ipynb
varunsingh4/MachineLearning
Results Analysis This notebook analyzes results produced by the _anti-entropy reinforcement learning_ experiments. The practical purpose of this notebook is to create graphs that can be used to display anti-entropy topologies, but also to extract information relevant to each experimental run.
%matplotlib notebook import os import re import glob import json import unicodedata import numpy as np import pandas as pd import seaborn as sns import networkx as nx import matplotlib as mpl import graph_tool.all as gt import matplotlib.pyplot as plt from nx2gt import nx2gt from datetime import timedelta fr...
_____no_output_____
MIT
fixtures/aerl/notebook/results-py3.ipynb
bbengfort/honu
Data Loading The data directory contains directories whose names are the hosts along with configuration files for each run. Each run is stored in its own `metrics.json` file, suffixed by the run number. The data loader yields _all_ rows from _all_ metric files and appends them with the correct configuration data.
DATA = "../data" FIGS = "../figures" GRAPHS = "../graphs" HOSTS = "hosts.json" RESULTS = "metrics-*.json" CONFIGS = "config-*.json" NULLDATE = "0001-01-01T00:00:00Z" DURATION = re.compile("^([\d\.]+)(\w+)$") def suffix(path): # Get the run id from the path name, _ = os.path.splitext(path) return int(name...
_____no_output_____
MIT
fixtures/aerl/notebook/results-py3.ipynb
bbengfort/honu
Graph Extraction This section extracts a NeworkX graph for each of the experimental runs such that each graph defines an anti-entropy topology.
def extract_graphs(path=DATA, outdir=None): graphs = defaultdict(nx.DiGraph) for row in load_results(path): # Get the graph for the topology G = graphs[row["runid"]] # Update the graph information name = row["bandit"]["strategy"].title() epsilon = row...
Annealing Epsilon Greedy (E5)
MIT
fixtures/aerl/notebook/results-py3.ipynb
bbengfort/honu
Rewards DataFrame This section extracts a timeseries of rewards on a per-replica basis.
def extract_rewards(path=DATA): for row in load_results(path): bandit = row["bandit"] history = bandit["history"] strategy = bandit["strategy"] epsilon = row["config"]["replicas"].get("epsilon") if epsilon: strategy += " ε={}".format(epsilon) values = np.a...
_____no_output_____
MIT
fixtures/aerl/notebook/results-py3.ipynb
bbengfort/honu
Choose GPU (this may not be needed on your computer)
%env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=1 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices)>0: tf.config.experimental.set_memory_growth(gpu_devices[0], True) print(gpu_devices) tf.keras.backend.clear_session()
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
load packages
from tfumap.umap import tfUMAP import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tqdm.autonotebook import tqdm import umap import pandas as pd
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Load dataset
dataset = 'fmnist' from tensorflow.keras.datasets import fashion_mnist # load dataset (train_images, Y_train), (test_images, Y_test) = fashion_mnist.load_data() X_train = (train_images/255.).astype('float32') X_test = (test_images/255.).astype('float32') X_train = X_train.reshape((len(X_train), np.product(np.shape(X_tr...
50000 10000 10000
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
define networks
dims = (28,28,1) n_components = 64 encoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=dims), tf.keras.layers.Conv2D( filters=64, kernel_size=3, strides=(2, 2), activation="relu" ), tf.keras.layers.Conv2D( filters=128, kernel_size=3, strides=(2, 2), activation="relu" ...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Plot model output
fig, ax = plt.subplots( figsize=(8, 8)) sc = ax.scatter( z[:, 0], z[:, 1], c=Y_train.astype(int)[:len(z)], cmap="tab10", s=0.1, alpha=0.5, rasterized=True, ) ax.axis('equal') ax.set_title("UMAP in Tensorflow embedding", fontsize=20) plt.colorbar(sc, ax=ax);
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
View loss
from tfumap.umap import retrieve_tensors import seaborn as sns
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Save output
from tfumap.paths import ensure_dir, MODEL_DIR output_dir = MODEL_DIR/'projections'/ dataset / '64' /'ae_only' ensure_dir(output_dir) encoder.save(output_dir / 'encoder') decoder.save(output_dir / 'encoder') #loss_df.to_pickle(output_dir / 'loss_df.pickle') np.save(output_dir / 'z.npy', z)
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
compute metrics
X_test.shape z_test = encoder.predict(X_test.reshape((len(X_test), 28,28,1)))
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
silhouette
from tfumap.silhouette import silhouette_score_block ss, sil_samp = silhouette_score_block(z, Y_train, n_jobs = -1) ss ss_test, sil_samp_test = silhouette_score_block(z_test, Y_test, n_jobs = -1) ss_test fig, axs = plt.subplots(ncols = 2, figsize=(10, 5)) axs[0].scatter(z[:, 0], z[:, 1], s=0.1, alpha=0.5, c=sil_samp, c...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
KNN
from sklearn.neighbors import KNeighborsClassifier neigh5 = KNeighborsClassifier(n_neighbors=5) neigh5.fit(z, Y_train) score_5nn = neigh5.score(z_test, Y_test) score_5nn neigh1 = KNeighborsClassifier(n_neighbors=1) neigh1.fit(z, Y_train) score_1nn = neigh1.score(z_test, Y_test) score_1nn
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Trustworthiness
from sklearn.manifold import trustworthiness tw = trustworthiness(X_train_flat[:10000], z[:10000]) tw_test = trustworthiness(X_test_flat[:10000], z_test[:10000]) tw, tw_test
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Save output metrics
from tfumap.paths import ensure_dir, MODEL_DIR, DATA_DIR
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
train
metrics_df = pd.DataFrame( columns=[ "dataset", "class_", "dim", "trustworthiness", "silhouette_score", "silhouette_samples", ] ) metrics_df.loc[len(metrics_df)] = [dataset, 'ae_only', n_components, tw, ss, sil_samp] metrics_df save_loc = DATA_DIR / 'projection_me...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
test
metrics_df_test = pd.DataFrame( columns=[ "dataset", "class_", "dim", "trustworthiness", "silhouette_score", "silhouette_samples", ] ) metrics_df_test.loc[len(metrics_df)] = [dataset, 'ae_only', n_components, tw_test, ss_test, sil_samp_test] metrics_df_test save_l...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
knn
nn_acc_df = pd.DataFrame(columns = ["method_","dimensions","dataset","1NN_acc","5NN_acc"]) nn_acc_df.loc[len(nn_acc_df)] = ['ae_only', n_components, dataset, score_1nn, score_5nn] nn_acc_df save_loc = DATA_DIR / 'knn_classifier' / 'ae_only' / 'train' / str(n_components) / (dataset + '.pickle') ensure_dir(save_loc) nn_...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Reconstruction
from sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error, r2_score X_recon = decoder.predict(encoder.predict(X_test.reshape((len(X_test), 28, 28, 1)))) X_real = X_test.reshape((len(X_test), 28, 28, 1)) x_real = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) x_recon = X...
_____no_output_____
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
Compute clustering quality
from sklearn.cluster import KMeans from sklearn.metrics import homogeneity_completeness_v_measure def get_cluster_metrics(row, n_init=5): # load cluster information save_loc = DATA_DIR / 'clustering_metric_df'/ ('_'.join([row.class_, str(row.dim), row.dataset]) + '.pickle') print(save_loc) if save_...
/mnt/cube/tsainbur/Projects/github_repos/umap_tf_networks/data/clustering_metric_df/ae_only_64_fmnist.pickle
MIT
notebooks/dataset-projections/64/fmnist/fmnist-64-ae-only.ipynb
timsainb/ParametricUMAP_paper
**Space X Falcon 9 First Stage Landing Prediction** Web scraping Falcon 9 and Falcon Heavy Launches Records from Wikipedia We will be performing web scraping to collect Falcon 9 historical launch records from a Wikipedia page titled `List of Falcon 9 and Falcon Heavy launches`[https://en.wikipedia.org/wiki/List_of_F...
!pip3 install beautifulsoup4 !pip3 install requests import sys import requests from bs4 import BeautifulSoup import re import unicodedata import pandas as pd
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Some helper functions for processing web scraped HTML table
def date_time(table_cells): """ This function returns the data and time from the HTML table cell Input: the element of a table data cell extracts extra row """ return [data_time.strip() for data_time in list(table_cells.strings)][0:2] def booster_version(table_cells): """ This function re...
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
To keep the lab tasks consistent, we will be asked to scrape the data from a snapshot of the `List of Falcon 9 and Falcon Heavy launches` Wikipage updated on`9th June 2021`
static_url = "https://en.wikipedia.org/w/index.php?title=List_of_Falcon_9_and_Falcon_Heavy_launches&oldid=1027686922"
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Next, request the HTML page from the above URL and get a `response` object TASK 1: Request the Falcon9 Launch Wiki page from its URL First, let's perform an HTTP GET method to request the Falcon9 Launch HTML page, as an HTTP response.
# use requests.get() method with the provided static_url # assign the response to a object page=requests.get(static_url)
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Create a `BeautifulSoup` object from the HTML `response`
# Use BeautifulSoup() to create a BeautifulSoup object from a response text content soup = BeautifulSoup(page.text, 'html.parser')
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Print the page title to verify if the `BeautifulSoup` object was created properly
# Use soup.title attribute soup.title
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
TASK 2: Extract all column/variable names from the HTML table header Next, we want to collect all relevant column names from the HTML table header Let's try to find all tables on the wiki page first.
# Use the find_all function in the BeautifulSoup object, with element type `table` # Assign the result to a list called `html_tables` html_tables=soup.find_all('table')
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Starting from the third table is our target table contains the actual launch records.
# Let's print the third table and check its content first_launch_table = html_tables[2] print(first_launch_table)
<table class="wikitable plainrowheaders collapsible" style="width: 100%;"> <tbody><tr> <th scope="col">Flight No. </th> <th scope="col">Date and<br/>time (<a href="/wiki/Coordinated_Universal_Time" title="Coordinated Universal Time">UTC</a>) </th> <th scope="col"><a href="/wiki/List_of_Falcon_9_first-stage_boosters" ti...
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
We can see the columns names embedded in the table header elements `` as follows: ```Flight No.Date andtime (UTC)Version,Booster [b]Launch sitePayload[c]Payload massOrbitCustomerLaunchoutcomeBoosterlanding``` Next, we just need to iterate through the `` elements and apply the provided `extract_column_from_header()` to ...
column_names = [] # Apply find_all() function with `th` element on first_launch_table # Iterate each th element and apply the provided extract_column_from_header() to get a column name # Append the Non-empty column name (`if name is not None and len(name) > 0`) into a list called column_names for i in first_launch_tab...
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Check the extracted column names
print(column_names)
['Flight No.', 'Date and time ( )', 'Launch site', 'Payload', 'Payload mass', 'Orbit', 'Customer', 'Launch outcome']
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
TASK 3: Create a data frame by parsing the launch HTML tables We will create an empty dictionary with keys from the extracted column names in the previous task. Later, this dictionary will be converted into a Pandas dataframe
launch_dict= dict.fromkeys(column_names) # Remove an irrelvant column del launch_dict['Date and time ( )'] # Let's initial the launch_dict with each value to be an empty list launch_dict['Flight No.'] = [] launch_dict['Launch site'] = [] launch_dict['Payload'] = [] launch_dict['Payload mass'] = [] launch_dict['Orbit'...
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
Next, we just need to fill up the `launch_dict` with launch records extracted from table rows. Usually, HTML tables in Wiki pages are likely to contain unexpected annotations and other types of noises, such as reference links `B0004.1[8]`, missing values `N/A [e]`, inconsistent formatting, etc.
extracted_row = 0 #Extract each table for table_number,table in enumerate(soup.find_all('table',"wikitable plainrowheaders collapsible")): # get table row for rows in table.find_all("tr"): #check to see if first table heading is as number corresponding to launch a number if rows.th: ...
1 4 June 2010 18:45 F9 v1.0B0003.1 CCAFS Dragon Spacecraft Qualification Unit 0 LEO SpaceX Success Failure ****** 2 8 December 2010 15:43 F9 v1.0B0004.1 CCAFS Dragon 0 LEO NASA Success Failure ****** 3 22 May 2012 07:44 F9 v1.0B0005.1 CCAFS Dragon 525 kg LEO NASA Success No attempt ****** 4 8 October 2012 00:35 F9 v1...
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
After we have filled in the parsed launch record values into `launch_dict`, we can create a dataframe from it.
df=pd.DataFrame(launch_dict) df.head()
_____no_output_____
Apache-2.0
spacex falcon 9 first stage landing prediction/web scraping for spacex falcon 9 first stage landing prediction.ipynb
HasibAlMuzdadid/Data-Science-Projects
LabelEncoderEncode labels with value between 0 and n_classes-1.
import warnings warnings.filterwarnings('ignore') from sklearn import preprocessing # call our labelEncoder class le = preprocessing.LabelEncoder() # fit our data le.fit([1, 2, 2, 6]) # print classes le.classes_ # transform le.transform([1, 1, 2, 6]) #print inverse data le.inverse_transform([0, 0, 1, 2]) le = preproce...
_____no_output_____
MIT
notebook - machine learning sklearn/ipython notebook/2017-25-11-so-preprocessing-encoding-categorical-features-sklearn.ipynb
bjfisica/MachineLearning
여러그림 그리기> 여러그림 그리기, Anscombe's quartet- toc: true- branch: master- badges: true- comments: true- author: dinonene- categories: [python] `-` (1/2) 여러그림그리기`-` (2/2) Anscombe's quartet 여러그림 그리기 (1) 겹쳐그리기
import numpy as np import matplotlib.pyplot as plt x=np.arange(-5,5,0.1) y=2*x+np.random.normal(loc=0,scale=1,size=100) plt.plot(x,y,'.b') plt.plot(x,2*x,'--r')
_____no_output_____
Apache-2.0
_notebooks/2022-01-02-plots.ipynb
pinkocto/dinonene
(2) 따로그리기 -subplots
x=[1,2,3,4] y=[1,2,4,3] _, axs = plt.subplots(2,2) axs[0,0].plot(x,y,'o:r') axs[0,1].plot(x,y,'xb') axs[1,0].plot(x,y,'xm') axs[1,1].plot(x,y,'.--k')
_____no_output_____
Apache-2.0
_notebooks/2022-01-02-plots.ipynb
pinkocto/dinonene
> note: fmt = `[marker][line][color]` ```pythonplt.subplots?? using the variable ax for single a Axes fig, ax = plt.subplots() using the variable axs for multiple Axes fig, axs = plt.subplots(2, 2) using tuple unpacking for multiple Axes fig, (ax1, a...
x = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5] y1 = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68] y2 = [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74] y3 = [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73] x4 = [8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8] y4 = [6.58, 5.76, 7...
_____no_output_____
Apache-2.0
_notebooks/2022-01-02-plots.ipynb
pinkocto/dinonene
`-` 상관계수를 잠깐 복습해보자.- 상관계수는 -1~1 사이의 값을 가진다. (코쉬슈바르츠 부등식을 사용하여 증명가능)- 완전한 직선이라면 상관계수가 1 또는 -1이다.- 상관계수가 1에 가까우면 양의 상관관계에 있다고 말하고 -1에 가까우면 음의 상관관계에 있다고 말한다. `-` 의문: 자료의 모양이 직선모양에 가까우면 상관계수가 큰 것이 맞나?- $x,y$ 값이 모두 큰 하나의 관측치가 상관계수값을 키울 수 있지 않나? `-` 상관계수가 좋은 것은 맞나? (=상관계수는 두 변수의 관계를 설명하기에 충분히 적절한 통계량인가?)
n=len(x) xtilde = (x-np.mean(x)) / (np.std(x)*np.sqrt(n)) ## x표준화 y1tilde = (y1-np.mean(y1)) / (np.std(y1)*np.sqrt(n)) ## y1표준화 sum(xtilde*y1tilde) np.corrcoef(x,y1) np.corrcoef([x,y1,y2,y3]) np.corrcoef([x4,y4])
_____no_output_____
Apache-2.0
_notebooks/2022-01-02-plots.ipynb
pinkocto/dinonene
Data Processing Stuff
df = pd.read_csv('D:\Data\processed.csv',delimiter = "\t",error_bad_lines=False) print(df.head(1)) # Clearning the Dataframe a bit df = df.drop(['Unnamed: 0','Unnamed: 0.1', 'Subject','user','labeled','To'], axis=1) df['label'] = df['rep'] df = df.drop(['rep'],axis=1) #df = df[df.label != 'unsup'] print(df.shape) # Tex...
Reached here X_train (74698, 70) y_train (74698,)
Apache-2.0
LSTM-Attention.ipynb
d1sharma/lign167
Neural Architecture begins here
# Defining the Model model = Sequential() model.add(Embedding(vocabulary_size,140,input_length=70)) model.add(LSTM(140, dropout =0.2, recurrent_dropout=0.3)) model.add(Activation('softmax')) model.add(Dense(1, activation='sigmoid')) print(model.summary()) # Compile the model model.compile(loss='binary_crossentropy',...
Test Accuracy: 0.832570281124498
Apache-2.0
LSTM-Attention.ipynb
d1sharma/lign167
Importing Important File regarding Analysis
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import datetime as dt import time import ipywidgets #from ipython.display import display data1 = pd.read_csv("covid_19_india (1).csv",dayfirst=True) data1
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
Data cleaning of Covid 19 india
missing_values = ["NaN","na","Na","-"] data1 = pd.read_csv("covid_19_india.csv",na_values= missing_values) data1.isnull().sum() #Now we have seen that "-" means empty values. Now we gonna fill this empty value with Zero because in terms of corona cases # it does not effect on our data data1 = data1.fillna(0) data1.loc...
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
State v/s Confirmed cases in India by Graph
for i in range(len(state)): new_date = latest_date[x:y+6] x+=6 y+=6 sns.set(rc = {'figure.figsize':(20,10)}) sns.barplot(x = "state", y = "confirmed", data = new_date, hue = "state") plt.show() #time.sleep(1) #Start date of cases is from 30-01-2020 and end date is 08-05-2021 of our data...
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
Visualising the statical data of covid 19 India Statewise Visualisation of (Confirmed vs Cured vs Death data of covid)
#Here we are making Daily cases column in our dataset and returning new dataframe named as result_data list1 = [] for i in range(len(state)): new_data = data1[data1.state == state.values[i]] x = 0 list = [] new_data = new_data.reset_index() new_data4 = new_data.confirmed.values[0] for j in range...
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
please select the state and different cases option to visualise your data
ipywidgets.interact(select, select = new_temp_state)
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
Here we are making our prediction based on each state
#using ipywidgets library to create dropdown option for user to easily select the query temp_value = ["confirmed","death","cured","daily_cases"] data_select3 = ipywidgets.Dropdown( options= temp_value, value=temp_value[0], description='Select option:', disabled=False, ...
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
*please select the option to avoid error *please note following things Confirmed cases is total confirmed cases untill selected day. Death cases is total death cases untill selected day. Cured cases is total Cures cases untill selected day. daily cases is the cases only of that day you select.
ipywidgets.interact(ultimate_prediction, predict = data_select3)
_____no_output_____
Apache-2.0
Covid_19_india_analysis (4).ipynb
singhrau0/Covid_19_india_predictor
FINAL PROJECT In the final project, you will create a closed loop system for an SBML model.Start by selecting a model from the [BioModels Curated branch](https://www.ebi.ac.uk/biomodels/search?query=*%3A*+AND+curationstatus%3A%22Manually+curated%22&domain=biomodels).)You don't have to restrict yourself to thoses model...
!pip install -q controlSBML import control import pandas as pd import matplotlib.pyplot as plt import numpy as np import tellurium as te
_____no_output_____
MIT
Assignments/Final-Project.ipynb
joseph-hellerstein/advanced-controls-lectures
Movielens EDA and Modeling> EDA and modeling on movielens dataset- toc: true- badges: true- comments: true- categories: [EDA, Movie, Visualization]- image: Setup
# download dataset !wget http://files.grouplens.org/datasets/movielens/ml-100k.zip && unzip ml-100k.zip !wget http://files.grouplens.org/datasets/movielens/ml-latest.zip && unzip ml-latest.zip import numpy as np import pandas as pd from datetime import datetime from collections import OrderedDict import gc import sys ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Loading
# loading ratings data names = ['user_id', 'item_id', 'rating', 'timestamp'] ratings_df = pd.read_csv('ml-100k/u.data', sep='\t', names=names) print('First 5:') display(ratings_df.head()) print() print('Last 5:') display(ratings_df.tail()) names = ["user_id", "age" , "gender","occupation", "zip_code"] user_df = pd.read...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Processed Data Loading
pratings = pd.read_csv(dpath+'ratings.csv', sep=',', encoding='latin-1') print('First 5:') display(pratings.head()) print() print('Last 5:') display(pratings.tail()) pmovies = pd.read_csv(dpath+'items.csv', sep=',', encoding='latin-1') print('First 5:') display(pmovies.head()) print() print('Last 5:') display(pmovies.t...
First 5:
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
EDA How are the ratings distributed?
norm_counts = ( ratings_df['rating'] .value_counts(normalize=True, sort=False) .multiply(100) .reset_index() .rename(columns={'rating': 'percent', 'index': 'rating'}) ) ax = sns.barplot(x='rating', y='percent', data=norm_counts) ax.set_title('Rating Frequencies') plt.show()
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
How many ratings were submitted per month?
def _process_ratings(ratings_df): ratings_df = ratings_df.copy() ratings_df['timestamp'] = ratings_df['timestamp'].apply(datetime.fromtimestamp) ratings_df['year'] = ratings_df['timestamp'].dt.year ratings_df['month'] = ratings_df['timestamp'].dt.month ratings_df = ratings_df.sort_values('timestamp') return...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
How consistent are the average ratings over time?
month_counts = _ratings_df.groupby(['year', 'month'])['rating'].agg([np.mean, np.std]) month_counts = month_counts.rename(index=str, columns={'mean': 'Rating'}) month_counts = month_counts.reset_index() month_counts['Date'] = month_counts[['year', 'month']].apply( lambda x: datetime(year=int(x[0]), month=int(x[1]),...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
How quickly do the movie and user bases grow over time?*(assume that a user has joined on her first rating, and that she remains a user from then on.)*
_ratings_df['Date'] = _ratings_df[['year', 'month']].apply( lambda x: datetime(year=int(x[0]), month=int(x[1]), day=1), axis=1 ) n_users = [] n_movies = [] dates = np.unique(_ratings_df['Date']) for date in dates: n_users.append(_ratings_df[_ratings_df['Date'] <= date]['user_id'].nunique()) n_movies.append(...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
How sparse is the user/movies matrix we'll be dealing with?
def get_rating_matrix(X): """Function to generate a ratings matrix and mappings for the user and item ids to the row and column indices Parameters ---------- X : pandas.DataFrame, shape=(n_ratings,>=3) First 3 columns must be in order of user, item, rating. Returns ------- rating...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Preprocessing
display(ratings_df.head())
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Baseline Models Baseline - Simple Average ModelThe first model we'll test is about the simplest one possible. We'll just average all the training set ratings and use that average for the prediction for all test set examples.
class SimpleAverageModel(): """A very simple model that just uses the average of the ratings in the training set as the prediction for the test set. Attributes ---------- mean : float Average of the training set ratings """ def __init__(self): pass def fit(self, X): ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Baseline - Average by ID ModelWe can probably do a little better by using the user or item (movie) average. Here we'll set up a baseline model class that allows you to pass either a list of userIds or movieIds as X. The prediction for a given ID will just be the average of ratings from that ID, or the overall average ...
class AverageByIdModel(): """Simple model that predicts based on average ratings for a given Id (movieId or userId) from training data Parameters ---------- id_column : string Name of id column (i.e. 'itemId', 'userId') to average by in dataframe that will be fitted to Attr...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Baseline - Damped Baseline with User + Movie DataThis baseline model takes into account the average ratings of both the user and the movie, as well as a damping factor that brings the baseline prediction closer to the overall mean. The damping factor has been shown empirically to improve the perfomance.This model foll...
class DampedUserMovieBaselineModel(): """Baseline model that of the form mu + b_u + b_i, where mu is the overall average, b_u is a damped user average rating residual, and b_i is a damped item (movie) average rating residual. See eqn 2.1 of http://files.grouplens.org/papers/FnT%20CF%20Recsys%20Surve...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
The MAE plots above show that the combined model with a damping factor of 0 or 10 performs the best, followed by the item average, then the user average. It makes sense that taking into account deviations from the mean due to both user and item would perform the best: there is simply more data being taken into account ...
# <!-- collapse=True --> class KNNRecommender(): """User-based or Item-based collaborative filtering model that operates on dataframes with at least a user-like, item-like, and a rating-like column Parameters ---------- mode : str, ['item | 'user'], default='item' Tells model whether to...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Determine Optimal k Values
def cart_prod(df_1, df_2): df_1['_dummy_'], df_2['_dummy_'] = 1, 1 return pd.merge(df_1, df_2, on='_dummy_').drop('_dummy_', axis=1) n_splits = 5 k_list = [1, 2, 5, 10, 20, 50, 100, 200] mode_list = ['user', 'item'] i_fold_list = np.arange(n_splits) df_1 = pd.DataFrame({'k': k_list}) df_2 = pd.DataFrame({'mod...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
ALS & SGD
class ALSRecommender(): """Recommender based on Alternating Least Squares algorithm. Parameters ---------- k : int, default=5 Number of latent features lmbda : float, default=0.1 Regularization parameter max_epochs : int, default=15 Max number of iterations to run ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook