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
Fetching the data from the source and looking at some higher level data
import nltk import pandas as pd #reading the messages from the source messages = [line.rstrip() for line in open('smsspamcollection/SMSSpamCollection')] messages[:10] #the messages can be red as Pandas dataframe fro easier operations messages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\t', names=['label'...
_____no_output_____
Unlicense
Spam Classifier.ipynb
pronoy-chatterjee/spam-classifier
Visualizing the data to find the most important predictor for the classification
import matplotlib.pyplot as plt %matplotlib inline messages['length'].hist(bins=150) messages['length'].describe() messages.hist(column='length', by='label', bins=60, figsize=(12, 4))
_____no_output_____
Unlicense
Spam Classifier.ipynb
pronoy-chatterjee/spam-classifier
By looking at the above plots we can say that the text length is one of the important deciding factors Text preprocessing before training the model
import string from nltk.corpus import stopwords #A function that takes input as a text and removes all the punctuations and stop words and returns a clean text def text_process(text): nopun = [c for c in text if c not in string.punctuation] nopun = ''.join(nopun) nopun = nopun.split() nostwords = [c for...
_____no_output_____
Unlicense
Spam Classifier.ipynb
pronoy-chatterjee/spam-classifier
Training and Evaluating the model
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split msg_train, msg_test, label_train, label_test = train_test_split(tfidf_messages, messages['label'], test_size=0.2) model = RandomForestClassifier() model.fit(msg_train, label_train) predictions = model.predict(msg_te...
precision recall f1-score support ham 0.96 1.00 0.98 976 spam 0.99 0.74 0.85 139 avg / total 0.97 0.97 0.96 1115
Unlicense
Spam Classifier.ipynb
pronoy-chatterjee/spam-classifier
RUN999 - Cleanup Master Pool runner infrastructure==================================================Description-----------Delete objects in the Big Data Cluster used for the runnerinfrastructure. Common functionsDefine helper functions used in this notebook.
# Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows import sys import os import re import json import platform import shlex import shutil import datetime from subprocess import Popen, PIPE from IPython.display import Markdown retry_hints = {} # Output in stderr...
_____no_output_____
MIT
Troubleshooting-Notebooks/Big-Data-Clusters/CU4/Public/content/notebook-runner/run999-cleanup-infrastructure.ipynb
nnpcYvIVl/tigertoolbox
Get the Kubernetes namespace for the big data clusterGet the namespace of the Big Data Cluster use the kubectl command lineinterface .**NOTE:**If there is more than one Big Data Cluster in the target Kubernetescluster, then either:- set \[0\] to the correct value for the big data cluster.- set the environment vari...
# Place Kubernetes namespace name for BDC into 'namespace' variable if "AZDATA_NAMESPACE" in os.environ: namespace = os.environ["AZDATA_NAMESPACE"] else: try: namespace = run(f'kubectl get namespace --selector=MSSQL_CLUSTER -o jsonpath={{.items[0].metadata.name}}', return_output=True) except: ...
_____no_output_____
MIT
Troubleshooting-Notebooks/Big-Data-Clusters/CU4/Public/content/notebook-runner/run999-cleanup-infrastructure.ipynb
nnpcYvIVl/tigertoolbox
Get the controller username and passwordGet the controller username and password from the Kubernetes SecretStore and place in the required AZDATA\_USERNAME and AZDATA\_PASSWORDenvironment variables.
# Place controller secret in AZDATA_USERNAME/AZDATA_PASSWORD environment variables import os, base64 os.environ["AZDATA_USERNAME"] = run(f'kubectl get secret/controller-login-secret -n {namespace} -o jsonpath={{.data.username}}', return_output=True) os.environ["AZDATA_USERNAME"] = base64.b64decode(os.environ["AZDATA_...
_____no_output_____
MIT
Troubleshooting-Notebooks/Big-Data-Clusters/CU4/Public/content/notebook-runner/run999-cleanup-infrastructure.ipynb
nnpcYvIVl/tigertoolbox
Drop database in `master pool` holding runner metrics
sql = f""" ALTER DATABASE [runner] SET SINGLE_USER WITH ROLLBACK IMMEDIATE """ try: run(f'azdata sql query --database master -q "{sql}"') except: # TODO: Fails on HA configuration with: # # The operation cannot be performed on database "runner" because it is # involved in a database mirroring session or an ...
_____no_output_____
MIT
Troubleshooting-Notebooks/Big-Data-Clusters/CU4/Public/content/notebook-runner/run999-cleanup-infrastructure.ipynb
nnpcYvIVl/tigertoolbox
Custom URL prefix with Seldon and AmbassadorThis notebook shows how you can deploy Seldon Deployments with custom Ambassador configuration.
from IPython.core.magic import register_line_cell_magic @register_line_cell_magic def writetemplate(line, cell): with open(line, "w") as f: f.write(cell.format(**globals())) VERSION = !cat ../../../version.txt VERSION = VERSION[0] VERSION
_____no_output_____
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
marianobilli/seldon-core
Setup Seldon CoreUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlSetup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlAmbassador) and [Install Seldon Core](https://doc...
%%writetemplate model_custom_ambassador.yaml apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: labels: app: seldon name: example-custom spec: annotations: seldon.io/ambassador-config: 'apiVersion: ambassador/v2 kind: Mapping name: seldon_example_rest_mapping ...
Waiting for deployment "example-custom-single-0-classifier" rollout to finish: 0 of 1 updated replicas are available... deployment "example-custom-single-0-classifier" successfully rolled out
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
marianobilli/seldon-core
Get predictions
from seldon_core.seldon_client import SeldonClient sc = SeldonClient(deployment_name="example-custom", namespace="seldon")
_____no_output_____
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
marianobilli/seldon-core
REST Request
r = sc.predict(gateway="ambassador", transport="rest", gateway_prefix="/mycompany/ml") assert r.success == True print(r) !kubectl delete -f model_custom_ambassador.json
error: the path "model_custom_ambassador.json" does not exist
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
marianobilli/seldon-core
Finding points of interest in an image
import numpy as np import matplotlib.pyplot as plt import skimage import skimage.feature as sf %matplotlib inline def show(img, cmap=None): cmap = cmap or plt.cm.gray fig, ax = plt.subplots(1, 1, figsize=(8, 6)) ax.imshow(img, cmap=cmap) ax.set_axis_off() return ax img = plt.imread('data/child.png')...
_____no_output_____
MIT
notebooks/D6_L2_Filtering/04_image_interest.ipynb
highrain2/myTestProjs
Pandas We have seen Numpy in the last section. It is good at performing math operations on 2d-arrays of numbers. But the major drawback is, it cannot deal with heterogeneous values. So, Pandas dataframes are helpful in that aspect for storing different data types and referring to the values like a dict in python inste...
# Import necessary libraries. import numpy as np import pandas as pd #Example series2 = pd.Series(data = [1,2,3], index = ['key1', 'key2', 'key3']) series2
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 1Convert a given dict to pd series.[**Hint:** Use **.Series**]
d1 = {'a': 1, 'b': 2, 'c': 3} # Create a dictionary with key-value pair. series1 = pd.Series(d1) # Dictionary to Pandas Series conversion. series1 # view the new series
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
You can directly use numpy functions on series. Question 2Find the dot product of both the series create above[ **Hint:** Use **np.dot()** ]
# Returns the dot product of vectors series1 and series2. It can handle 2D arrays but considering them as matrix and will perform matrix multiplication. np.dot(series1, series2)
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Dataframes A dataframe is a table with labeled columns which can hold different types of data in each column.
# Example d1 = {'a': [1,2,3], 'b': [3,4,5], 'c':[6,7,8] } df1 = pd.DataFrame(d1) df1
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 3Select second row in the above dataframe df1.
df1.loc[[1,]] # selects row=1 and all columns of df1.
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 4Select column c in second row of df1.[ **Hint:** For using labels use **df.loc[row, column]**. For using numeric indexes use **df.iloc[]**. ]
df1.loc[1, 'c'] # using df.loc[row, column], where row=1, and column='c'.
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Using Dataframes on a dataset Using the mtcars dataset.For the below set of questions, we will be using the cars data from [Motor Trend Car Road Tests](http://stat.ethz.ch/R-manual/R-devel/library/datasets/html/mtcars.html)The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption an...
# Reading a dataset from a csv file using pandas. mtcars = pd.read_csv('mtcars.csv') mtcars.index = mtcars['name']
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Following questions are based on analysing a particular dataset using pandas dataframes. Question 5Check the type and dimensions of the given dataset (mtcars).[ **Hint:** Use **type()** and **df.shape** ]
mtcars.shape type(mtcars)
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 6Check the first 10 lines and last 10 lines of the given dataset (mtcars).[ **Hint:** Use **.head()** and **.tail()** ]
mtcars.head(10) mtcars.tail(10)
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 7Print all the column labels in the given dataset (mtcars).
mtcars.columns
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 8 Select first 6 rows and 3 columns in mtcars dataset.[ **Hint:** **mtcars.iloc[ : , : ]** gives all rows and columns in the dataset ]
mtcars.iloc[0:6,0:3]
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 9 Select rows from name **Mazda RX4** to **Valiant** in the mtcars dataset and display only mpg and cyl values of those cars. [ **Hint:** Use **iloc or loc** ].
mtcars.iloc[0:6, 1:3] mtcars.loc['Mazda RX4':'Valiant', 'mpg':'cyl']
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 10Sort the dataframe by mpg (i.e. miles/gallon):[ **Hint**: **inplace = True** will make changes to the data ]
mtcars.sort_values(by=['mpg'], ascending=False, inplace=False)
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 11Print the mean displacement and horsepower of the cars grouped by the number of cylinders.
mtcars.groupby('cyl')[['disp','hp']].mean()
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 12Create a new column in the dataframe whose value will be 1 if the car is of Toyota company and 0 otherwise.
mtcars['name_Toyota'] = 0 for item in mtcars.index: if 'Toyota' in mtcars.loc[item, 'name']: mtcars.loc[item, 'name_Toyota'] = 1 mtcars # or you can use list comprehension mtcars['name_Toyota'] = [1 if 'Toyota' in item else 0 for item in mtcars.name] mtcars
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
Question 13Define a function that will multiply all values in a column by 4, and apply it to the qsec column.
# function to multiply all values by 4 def mul_by_4(col): return col*4 mtcars['qsec'].apply(mul_by_4) # you can also use a lambda function mtcars['qsec'].apply(lambda x: x*4)
_____no_output_____
MIT
notebooks/PE_Pandas_Solution.ipynb
NickBaynham/aimldl
![DoctorBert](https://snag.gy/oF84Gk.jpg)![DoctorBert](https://i.ytimg.com/vi/nPemP-Q0Xn8/hqdefault.jpg)This is a Colab Demo of our DocProduct Tensorflow 2.0 Hackathon ProjectProject details can be seen on our Github repohttps://github.com/Santosh-Gupta/DocProductand our Devpost pagehttps://devpost.com/software/nlp-doc...
from IPython.display import HTML, display def set_css(): display(HTML(''' <style> pre { white-space: pre-wrap; } </style> ''')) get_ipython().events.register('pre_run_cell', set_css) #@title Install Faiss, TF 2.0, and our Github. Double Click to see code #To use CPU FAISS use !wget https://an...
_____no_output_____
MIT
medical_questions/ForHPI_DocProductPresentationV6-0.2.0.ipynb
Ijusttyped/HPI_Documents
Read data
def read_data(path: str, n: int = 100_000_000, filter_ids = None) -> pd.DataFrame: items = [] with open(path, 'r') as data_file: for _ in tqdm(range(n)): line = data_file.readline() if not line: break json_line = json.loads(line) if f...
_____no_output_____
MIT
notebooks/eda_books.ipynb
feeeper/hw-recsys
EDA Ratings distribution
px.bar(books[['asin', 'overall']].groupby('overall').agg({'overall': 'count'}))
_____no_output_____
MIT
notebooks/eda_books.ipynb
feeeper/hw-recsys
Ratings distribution by category (for twenty most popupal categories)
from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=5, cols=4) i = 0 j = 1 for cat in twenty_most_popular_categories_names: i += 1 if i % 5 == 0: j += 1 i = 1 cat = cat.replace(' ', '_').replace('&', 'and').replace(',', '_') gr = bo...
_____no_output_____
MIT
notebooks/eda_books.ipynb
feeeper/hw-recsys
Summary report
def summary(data: pd.DataFrame) -> None: from IPython.display import display, Markdown percentiles = [5, 25, 50, 75, 95] unique_books_count = books["asin"].nunique() unique_users = books['reviewerID'].nunique() average_rating = books['overall'].mean() meadian_rating = books['overall'].median() ...
_____no_output_____
MIT
notebooks/eda_books.ipynb
feeeper/hw-recsys
This Notebook Covers- Scraping the profiles of the student data from Yocket for 29 Universities- The dataset has graduate student details for Admit and Reject for Computer Science Deaprtment
# importing libraries import requests from bs4 import BeautifulSoup import pandas as pd import pandas as pd from selenium import webdriver import time from bs4 import BeautifulSoup from selenium.webdriver.chrome.options import Options from fake_useragent import UserAgent # creating global varibale for storing of the sp...
_____no_output_____
MIT
Final Project _ Graduate Admission Predictor/Code/Scraping/Edulix_scrapper.ipynb
satwik2663/Machine-Learning---Graduate-Stduent-Predictor
Scraping Edulix data for multiple university- we will use the entire scraped university list to get the profile data for the 29 Universities
options = Options() ua = UserAgent() userAgent = ua.random options.add_argument(f'user-agent={userAgent}') driver = webdriver.Chrome(chrome_options=options, executable_path = 'chromedriver.exe') driver.get('https://www.edulix.com/') time.sleep(30) driver.get('https://www.edulix.com/' + 'share-profile/93397') #page = ...
_____no_output_____
MIT
Final Project _ Graduate Admission Predictor/Code/Scraping/Edulix_scrapper.ipynb
satwik2663/Machine-Learning---Graduate-Stduent-Predictor
Edulix : CSV file
Edulix_Reject_data_all_college = pd.read_csv(r'..\..\data\Edulix_admission_records.csv') Edulix_Reject_data_all_college.columns.values
_____no_output_____
MIT
Final Project _ Graduate Admission Predictor/Code/Scraping/Edulix_scrapper.ipynb
satwik2663/Machine-Learning---Graduate-Stduent-Predictor
Introduction to Data Science Activity for Lecture 9: Linear Regression 1*COMP 5360 / MATH 4100, University of Utah, http://datasciencecourse.net/*Name: Vishwa MurugappanEmail: u1089366@umail.utah.eduUID: u1089366 Class exercise: amphetamine and appetiteAmphetamine is a drug that suppresses appetite. In a study of th...
# imports and setup import scipy as sc import numpy as np import pandas as pd import statsmodels.formula.api as sm from sklearn import linear_model import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10, 6) from mpl_toolkits.mplot3d import Axes3D from matplotlib impor...
_____no_output_____
MIT
09-LinearRegression1/09-LinearRegression1_Activity.ipynb
VishMur/2022-datascience-lectures
Activity 1: Scatterplot and Linear Regression**Exercise:** Make a scatter plot with dose as the $x$-variable and food consumption as the $y$ variable. Then run a linear regression on the data using the 'ols' function from the statsmodels python library to relate the variables by $$\text{Food Consumption} = \beta_0 + \...
# your code goes here plt.scatter()
_____no_output_____
MIT
09-LinearRegression1/09-LinearRegression1_Activity.ipynb
VishMur/2022-datascience-lectures
**Your answer goes here:** Activity 2: ResidualsThe regression in Activity 1 is in fact valid even though the predictor $x$ only has 3 distinct values; for each fixed value of $x$, the researcher collected a random sample of $y$ values.However, one assumption which is made by simple linear regression is that the resid...
# your code goes here
_____no_output_____
MIT
09-LinearRegression1/09-LinearRegression1_Activity.ipynb
VishMur/2022-datascience-lectures
Download script for OMI dataExample of how to download monthly summaries of asc.gz files from temis.nl server
import os from glob import glob import wget import pandas as pd import requests from tqdm import * def make_url(year, month, kind): """Create url from a year and month string as a download link""" base = "http://temis.nl/airpollution/no2col/data/omi/data_v2/" file_start = "no2_" return ''.join([base, ye...
_____no_output_____
MIT
omi_download.ipynb
adrian-rosu-90/data_download
If there is no Data/ folder in the local folder, one will be madeif the [year][month].asc.gz file doesnt exist on the server no download will be attempted, and instead an Eror will be raised.(This is so you can use a try: except: syntax to run a loop.) Download multiple filesTo download multiple files you will need to ...
def download_batch(start, end, kind): """ Provide a start and and end date. A local Data folder will be created if none exists. All files present in temis.nl/airpollution/no2col/data/omi/data_v2/ will be downloaded there. (Even though dates are given to days, the time steps are monthly.) ...
_____no_output_____
MIT
omi_download.ipynb
adrian-rosu-90/data_download
Networks: structure, evolution & processes**Internet Analytics - Lab 2 helper**In this notebook, you can find snippets of Python code to help you solve the exercises of the lab.--- 2.2 Network SamplingYou can use the library [`requests`](http://docs.python-requests.org/en/master/) to extract information about a node a...
import requests # Base url of the API URL_TEMPLATE = 'http://iccluster118.iccluster.epfl.ch:5050/v1.0/facebook?user={user_id}' # Target user id user_id = 'f30ff3966f16ed62f5165a229a19b319' # The actual url to call url = URL_TEMPLATE.format(user_id=user_id) # Execute the HTTP Get request response = requests.get(url) # ...
_____no_output_____
MIT
ix-lab2/notebooks/ix-lab2-helper.ipynb
emlg/Internet-Analytics
--- 2.3 Epidemics SimulationWe provide you with the module `epidemics_helper` including a Python class `SimulationSIR` to simulate epidemics. Read the documentation of the code if you have additional questions concerning its behavior.
import epidemics_helper
_____no_output_____
MIT
ix-lab2/notebooks/ix-lab2-helper.ipynb
emlg/Internet-Analytics
The `SimulationSIR` object can simulate continuous-time [SIR] epidemics propagating over a network. To initialize it, you need to provide 3 parameters:* A graph `G` of type `networkx.Graph` over which the epidemic propagates,* The parameter $\beta$ of type `float` corresponding to the rate of infection at which nodes i...
G = # ... YOUR CODE HERE ... sir = epidemics_helper.SimulationSIR(G, beta=100.0, gamma=1.0)
_____no_output_____
MIT
ix-lab2/notebooks/ix-lab2-helper.ipynb
emlg/Internet-Analytics
To start the simulation, use the function `launch_epidemic` which takes as input the source node `source`, and the maximum duration `max_time` the epidemic needs to run for.
sir.launch_epidemic(source=0, max_time=100.0)
_____no_output_____
MIT
ix-lab2/notebooks/ix-lab2-helper.ipynb
emlg/Internet-Analytics
You may want to extract the time of infection (resp. recovery) of each nodes, accessible by the `SimulationSIR` attribute `inf_time` (resp. `rec_time`). Both attribute are `Numpy` one-dimensional arrays of length $N$ (i.e. the number of nodes in the graph).To get the infection time of node `i`, type:```sir.inf_time[i]`...
node_id = 123 print('Node: ', node_id) print('Infection time: ', sir.inf_time[node_id]) print('Recovery time: ', sir.rec_time[node_id])
_____no_output_____
MIT
ix-lab2/notebooks/ix-lab2-helper.ipynb
emlg/Internet-Analytics
DEtection TRansformer Network --- 1. Import Modules
%load_ext autoreload %autoreload 2 from detr_models.detr.model import DETR from detr_models.detr.train import get_image_information from detr_models.detr.config import DefaultDETRConfig from detr_models.backbone.backbone import Backbone from detr_models.detr.utils import create_positional_encodings import tensorflow...
The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload
MIT
notebooks/DETR_Inference.ipynb
keyofdeath/detr-tensorflow
--- 2. Specify required paths
# Specify model path path = input(prompt='Please specify the storage path:\n') # Specify image path image_path = input(prompt='Please specify the storage path:\n')
_____no_output_____
MIT
notebooks/DETR_Inference.ipynb
keyofdeath/detr-tensorflow
--- 3. Load Model
model = tf.keras.models.load_model(path) model.summary()
_____no_output_____
MIT
notebooks/DETR_Inference.ipynb
keyofdeath/detr-tensorflow
--- 4. Load Data
# Load Config config = DefaultDETRConfig() fm_shape=model.get_layer("Backbone").output.shape[1::] positional_encodings = create_positional_encodings(fm_shape, config.dim_transformer//2, batch_size=1) image = img_to_array(load_img(image_path), dtype=np.float32) image = np.expand_dims(image,0) print(positional_encodi...
_____no_output_____
MIT
notebooks/DETR_Inference.ipynb
keyofdeath/detr-tensorflow
--- 5. Inference
%%time detr_scores, detr_bbox = model([image, positional_encodings], training=False) print(detr_scores.shape) print(detr_bbox.shape)
_____no_output_____
MIT
notebooks/DETR_Inference.ipynb
keyofdeath/detr-tensorflow
Data ReaderPickled object is stored in the shared physical memory. Therefore, `read_from_shared_memory` returns a copy of pandas object saved in memory by `loader` process. Pickling will not serve well for large data. However, we aren't short of RAM and **this approach is 135% faster on a 2GB dataset**.
import mmap import pickle import posix_ipc as ipc import pandas as pd # variables.. shared_memory_name = "/shared-memory-bucket" data_file = "data-01.txt"
_____no_output_____
MIT
shared-memory/reader.ipynb
shengoneconnect/buffet
Description
def get_file_size(path): with open(path) as f: io = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) return io.size() print("File: ", data_file) print("Type: ", "text/csv") print("Size: ", get_file_size(data_file) / 10**6, "MB")
File: data-01.txt Type: text/csv Size: 2504.015418 MB
MIT
shared-memory/reader.ipynb
shengoneconnect/buffet
1. Read from shared memory created by Loader
def read_from_shared_memory(name): memory = ipc.SharedMemory(name=name) io = mmap.mmap(memory.fd, memory.size, mmap.MAP_SHARED, mmap.PROT_READ) bytes_obj = io.read() obj = pickle.loads(bytes_obj) io.close() memory.close_fd() return obj %%timeit df = read_from_shared_memory(shared_memory_name...
_____no_output_____
MIT
shared-memory/reader.ipynb
shengoneconnect/buffet
2. Read from disk
%%timeit pd.read_table(data_file, header=None)
32.9 s ± 259 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
MIT
shared-memory/reader.ipynb
shengoneconnect/buffet
CER002 - Download existing Root CA certificate==============================================Use this notebook to download a generated Root CA certificate from acluster that installed one using:- [CER001 - Generate a Root CA certificate](../cert-management/cer001-create-root-ca.ipynb)And then to upload the generate...
local_folder_name = "mssql-cluster-root-ca" test_cert_store_root = "/var/opt/secrets/test-certificates"
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Common functionsDefine helper functions used in this notebook.
# Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows import sys import os import re import json import platform import shlex import shutil import datetime from subprocess import Popen, PIPE from IPython.display import Markdown retry_hints = {} # Output in stderr...
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Get the Kubernetes namespace for the big data clusterGet the namespace of the Big Data Cluster use the kubectl command lineinterface .**NOTE:**If there is more than one Big Data Cluster in the target Kubernetescluster, then either:- set \[0\] to the correct value for the big data cluster.- set the environment vari...
# Place Kubernetes namespace name for BDC into 'namespace' variable if "AZDATA_NAMESPACE" in os.environ: namespace = os.environ["AZDATA_NAMESPACE"] else: try: namespace = run(f'kubectl get namespace --selector=MSSQL_CLUSTER -o jsonpath={{.items[0].metadata.name}}', return_output=True) except: ...
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Get name of the ‘Running’ `controller` `pod`
# Place the name of the 'Running' controller pod in variable `controller` controller = run(f'kubectl get pod --selector=app=controller -n {namespace} -o jsonpath={{.items[0].metadata.name}} --field-selector=status.phase=Running', return_output=True) print(f"Controller pod name: {controller}")
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Create a temporary folder to hold Root CA certificate
import os import tempfile import shutil path = os.path.join(tempfile.gettempdir(), local_folder_name) if os.path.isdir(path): shutil.rmtree(path) os.mkdir(path)
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Copy Root CA certificate from `controller` `pod`
import os cwd = os.getcwd() os.chdir(path) # Workaround kubectl bug on Windows, can't put c:\ on kubectl cp cmd line run(f'kubectl cp {controller}:{test_cert_store_root}/cacert.pem cacert.pem -c controller -n {namespace}') run(f'kubectl cp {controller}:{test_cert_store_root}/cakey.pem cakey.pem -c controller -n {nam...
_____no_output_____
MIT
Big-Data-Clusters/CU8/Public/content/cert-management/cer002-download-existing-root-ca.ipynb
DiHo78/tigertoolbox
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. RBM Deep Dive with Tensorflow In this notebook we provide a complete walkthrough of the Restricted Boltzmann Machine (RBM) algorithm with applications to recommender systems. In particular, we use as a case study the [movielens da...
from __future__ import print_function from __future__ import absolute_import from __future__ import division # set the environment path to find Recommenders import sys sys.path.append("../../") import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import papermill #RBM...
System version: 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 19:16:44) [GCC 7.3.0] Pandas version: 0.23.4
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
1. RBM Theory 1.1 Overview and main differences with other recommender algorithmsA Restricted Boltzmann Machine (RBM) is an undirected graphical model originally devised to study the statistical mechanics (or physics) of magnetic systems. Statistical mechanics (SM) provides a probabilistic description of complex syst...
MOVIELENS_DATA_SIZE = '100k' mldf_100k = movielens.load_pandas_df( size=MOVIELENS_DATA_SIZE, header=['userID','movieID','rating','timestamp'] ) # Convert the float precision to 32-bit in order to reduce memory consumption mldf_100k.loc[:, 'rating'] = mldf_100k['rating'].astype(np.int32) mldf_100k.head() MO...
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
3.1 Split the data using the stratified splitter As a second step, we split the data into train and test set by mantaining the same matrix size. Clearly, the two matrices will contain different ratings in different proportions. - First, we use the `AffinityMatrix` class to generate the $(m,n)$ user/affinity matrix $...
#to use standard names across the analysis header = { "col_user": "userID", "col_item": "movieID", "col_rating": "rating", } #instantiate the splitter am1m = AffinityMatrix(DF = mldf_1m, **header) #obtain the sparse matrix X1m = am1m.gen_affinity_matrix()
Generating the user/item affinity matrix... Matrix generated, sparseness percentage: 95
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
Next, we split the matrix above into train and test set sparse matrices
Xtr_1m, Xtst_1m = numpy_stratified_split(X1m)
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
It is useful to inspect the distribution of ratings in the test/train matrix to make sure that the splitter keeps it constant. We can inspect this by plotting the normalized histograms
_, (ax1m, ax2m) = plt.subplots(1, 2, sharey=True, figsize=(10,5)) ax1m.hist(Xtr_1m[Xtr_1m !=0], 5, density= True) ax1m.set_title('Train') ax1m.set(xlabel="ratings", ylabel="density") ax2m.hist(Xtst_1m[Xtst_1m !=0], 5, density= True) ax2m.set_title('Test') ax2m.set(xlabel="ratings", ylabel="density")
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
We now repeat the same operations for the other datasets
#100k am100k = AffinityMatrix(DF = mldf_100k, **header) X100k= am100k.gen_affinity_matrix() Xtr_100k, Xtst_100k = numpy_stratified_split(X100k) _, (ax1k, ax2k) = plt.subplots(1, 2, sharey=True, figsize=(10,5)) ax1k.hist(Xtr_100k[Xtr_100k !=0], 5, density= True) ax1k.set_title('Train') ax1k.set(xlabel="ratings", ylabel=...
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
From the plots above we can see that the two datasets have very similar rating distributions. The main difference is in the degree of sparsness of the user/item affinity matrix; this is an important factor as it states the ratio between datapoints and unrated movies to infere. Note that the split function returns the t...
#collection of evaluation metrics for later use def ranking_metrics( data_size, data_true, data_pred, time_train, time_test, K ): eval_map = map_at_k(data_true, data_pred, col_user="userID", col_item="movieID", col_rating="rating", col_prediction="prediction", ...
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
4. Model application, performance and analysis of the results The model has been implemented as a Tensorflow (TF) class with the TF session hidden inside the `fit()` method, so that no explicit call is needed. The algorithm operates in three different steps: - Model initialization: This is where we tell TF how to bui...
#First we initialize the model class model_1m = RBM(hidden_units= 1200, training_epoch = 30, minibatch_size= 350, with_metrics=True)
TensorFlow version: 1.12.0
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
Note that the first time the fit method is called it may take longer to return the result. This is due to the fact that TF needs to initialized the GPU session. You will notice that this is not the case when training the algorithm the second or more times. As for the `minibatch_size`, you would like to choose a value t...
#Model Fit train_time = model_1m.fit(Xtr_1m, Xtst_1m)
Creating the computational graph Initialize Gibbs protocol training epoch 0 rmse 0.961369 training epoch 10 rmse 0.902065 training epoch 20 rmse 0.864718 training epoch 30 rmse 0.848415 done training, Training time 10.9566452 Train set accuracy 0.3561482 Test set accuracy 0.3516242
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
During training, we evauate the root mean squared error to have an idea of how learning is proceeding. Remember that in the RBM this is not the quantity being minimized, but plotting the rmse per epoch gives us a rough understanding of how learning is proceeding and how we should adjust the hyper parameters. Generally,...
#number of top score elements to be recommended K = 10 #Model prediction on the test set Xtst. top_k_1m, test_time = model_1m.recommend_k_items(Xtst_1m)
/anaconda/envs/reco_full/lib/python3.6/site-packages/numpy/core/fromnumeric.py:83: RuntimeWarning: invalid value encountered in reduce return ufunc.reduce(obj, axis, dtype, out, **passkwargs) Extracting top 10 elements Done recommending items, time 1.7780292
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
top_k returns the first K elements having the highest recommendation score. Here the recommendation score is evaluated by multiplying the predicted rating by its probability, i.e. the confidence the algorithm has about its output. So if we have two items both with predicted ratings 5, but one with probability 0.5 and t...
top_k_df_1m = am1m.map_back_sparse(top_k_1m, kind = 'prediction') test_df_1m = am1m.map_back_sparse(Xtst_1m, kind = 'ratings') rating_1m= ranking_metrics( data_size = "mv 1m", data_true =test_df_1m, data_pred =top_k_df_1m, time_train=train_time, time_test =test_time, K =10) rating_1m
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
Formally, one should train the model until the cost function becomes flat but often an "early stopping" does the job. In the above example, we decided to train the algorithm to achieve higher ranking metrics. A faster optimization will do as well, but it will decrease the ranking metrics. 4.2 100k Dataset
#100k model_100k = RBM(hidden_units= 600, training_epoch = 30, minibatch_size= 60,keep_prob= 0.9, with_metrics = True) train_time = model_100k.fit(Xtr_100k, Xtst_100k) #Model prediction on the test set Xtst. top_k_100k, test_time = model_100k.recommend_k_items(Xtst_100k) #to df top_k_df_100k = am100k.map_back_sparse...
Extracting top 10 elements Done recommending items, time 0.1804592
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
4.2.1 Model evaluation
eval_100k= ranking_metrics( data_size = "mv 100k", data_true =test_df_100k, data_pred =top_k_df_100k, time_train=train_time, time_test =test_time, K=10) eval_100k
_____no_output_____
MIT
examples/02_model_collaborative_filtering/rbm_deep_dive.ipynb
zhanchao019/recommenders
Base case: Empty array then return -1Induction Hypothesis: If smaller list talks the correct 1st index of xInduction Step: Check if 1st place is x or not if found then return 0 else find x in rest of the list
def firstIndex(arr, si, x): l = len(arr) if l == 0: return -1 if arr[si] == x: return si return firstIndex(arr, si+1, x) arr = [1,0,1,0,1,0,6,4,9,4] x = 4 print(firstIndex(arr, 0, x)) # Make a copy of an array def firstIndex(arr, x): l = len(arr) if l == 0: return -1 ...
_____no_output_____
Unlicense
01 Recursion-1/7 Find Index of number.ipynb
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
Bias----------------------------------------Bias - HyperStat Onlinehttp://davidmlane.com/hyperstat/A9257.htmlA statistic is biased if, in the long run, it consistently over or underestimates the parameter it is estimating. More technically it is biased if its expected value is not equal to the parameter. A stop watch ...
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.stats as ss import seaborn as sns plt.style.use('ggplot') # R statistical style plt.rcParams['figure.figsize'] = 14, 10
_____no_output_____
Apache-2.0
Statistical-bias.ipynb
Datagatherer2357/Statistical-bias
Location and scale
x = np.linspace(-10.0, 10.0, 1000) plt.fill(x, ss.norm.pdf(x, loc= 0.0, scale=1.0), label="$\mu = 0.0, \sigma = 1.0$", c='b', alpha=0.6, lw=3.0) plt.fill(x, ss.norm.pdf(x, loc= 2.0, scale=1.0), label="$\mu = 2.0, \sigma = 1.0$", c='r', alpha=0.6, lw=3.0) plt.fill(x, ss.norm.pdf(x, loc= 0.0, scale=2.0), label="$\mu = 0...
_____no_output_____
Apache-2.0
Statistical-bias.ipynb
Datagatherer2357/Statistical-bias
These curves represent bell shape curves. The blue and red curves go on to infinity on the x axis. All we are really interested in is the M and SD. No matter what the M and SD are, if you go out 1 SD left and right, 68.27% of the distribution scores lie here, for 2 SD its 95.45%, 3 SDs is 99.7%. Probability
x = np.linspace(-3.0, 3.0, 1000) y = ss.norm.pdf(x, loc= 0.0, scale=1.0) xseg = x[np.logical_and(-1.0 < x, x < 1.4)] yseg = y[np.logical_and(-1.0 < x, x < 1.4)] plt.plot(x, y, color='k', alpha=0.5) plt.fill_between(xseg, yseg, color='b', alpha=0.5) plt.axvline(x=-1.0, color='grey', linestyle=':') plt.axvline(x= 1.4...
_____no_output_____
Apache-2.0
Statistical-bias.ipynb
Datagatherer2357/Statistical-bias
Sampling distribution
np.set_printoptions(formatter={'float': lambda x: "{0:6.3f}".format(x)}) sampsize = 10 nosamps = 1000 # Thus 1000 samples or 10 persons heights samp = np.random.standard_normal((nosamps, sampsize)) print(samp) mean = samp.sum(axis=1) / sampsize print(mean) # prints out all of the different means from all of the diff...
[ 0.479 -0.178 0.184 -0.333 -0.348 -0.043 0.163 -0.295 0.205 -0.632 0.417 0.045 -0.240 -0.081 0.191 0.357 -0.013 0.085 0.044 -0.132 0.131 -0.104 -0.128 -0.186 0.364 -0.480 -0.080 0.745 -0.404 0.454 0.199 -0.154 0.073 0.208 -0.473 -0.155 -0.123 0.136 -0.284 -0.153 0.512 0.019 -0.221 0.120 -0.366 ...
Apache-2.0
Statistical-bias.ipynb
Datagatherer2357/Statistical-bias
Heres where it ties into BIAS:If you work out a population variance.
# Calculate the variance. (Square of the SD) # Q: How do we get the variance?: # ANS: Take the mean from each of the values then square all othe values and add them together and then # divide by the number of values you started with.... # BUT !! This method is biased because it typically UNDERESTIMATES the real sampli...
_____no_output_____
Apache-2.0
Statistical-bias.ipynb
Datagatherer2357/Statistical-bias
Lab 01 : LeNet5 ChebGCNs - demo Spectral Graph ConvNetsConvolutional Neural Networks on Graphs with Fast Localized Spectral FilteringM Defferrard, X Bresson, P VandergheynstAdvances in Neural Information Processing Systems, 3844-3852, 2016ArXiv preprint: [arXiv:1606.09375](https://arxiv.org/pdf/1606.09375.pdf)
# For Google Colaboratory import sys, os if 'google.colab' in sys.modules: # mount google drive from google.colab import drive drive.mount('/content/gdrive') # find automatically the path of the folder containing "file_name" : file_name = '02_ChebGCNs.ipynb' import subprocess path_to_file = ...
cuda not available
MIT
codes/labs_lecture14/lab01_ChebGCNs/02_ChebGCNs.ipynb
kangjie-chen/CE7454_2020
MNIST
def check_mnist_dataset_exists(path_data='./'): flag_train_data = os.path.isfile(path_data + 'mnist/train_data.pt') flag_train_label = os.path.isfile(path_data + 'mnist/train_label.pt') flag_test_data = os.path.isfile(path_data + 'mnist/test_data.pt') flag_test_label = os.path.isfile(path_data + 'mni...
(500, 784) (500,) (100, 784) (100,)
MIT
codes/labs_lecture14/lab01_ChebGCNs/02_ChebGCNs.ipynb
kangjie-chen/CE7454_2020
Graph Adjacency Matrix
from lib.grid_graph import grid_graph from lib.coarsening import coarsen from lib.coarsening import lmax_L from lib.coarsening import perm_data from lib.coarsening import rescale_L # Construct graph t_start = time.time() grid_side = 28 number_edges = 8 metric = 'euclidean' ######## YOUR GRAPH ADJACENCY MATRIX HERE #...
nb edges: 6396 Heavy Edge Matching coarsening with Xavier version Layer 0: M_0 = |V| = 944 nodes (160 added), |E| = 3198 edges Layer 1: M_1 = |V| = 472 nodes (67 added), |E| = 1619 edges Layer 2: M_2 = |V| = 236 nodes (23 added), |E| = 784 edges Layer 3: M_3 = |V| = 118 nodes (5 added), |E| = 387 edges Layer 4: M_4 = ...
MIT
codes/labs_lecture14/lab01_ChebGCNs/02_ChebGCNs.ipynb
kangjie-chen/CE7454_2020
LeNet5 ChebGCNs Layers: CL32-MP4-CL64-MP4-FC512-FC10
# class definitions class my_sparse_mm(torch.autograd.Function): """ Implementation of a new autograd function for sparse variables, called "my_sparse_mm", by subclassing torch.autograd.Function and implementing the forward and backward passes. """ @staticmethod def forward(self, W, ...
Delete existing network Graph ConvNet: LeNet5 nb of parameters= 1991050 Graph_ConvNet_LeNet5( (cl1): Linear(in_features=25, out_features=32, bias=True) (cl2): Linear(in_features=800, out_features=64, bias=True) (fc1): Linear(in_features=3776, out_features=512, bias=True) (fc2): Linear(in_features=512, out_fe...
MIT
codes/labs_lecture14/lab01_ChebGCNs/02_ChebGCNs.ipynb
kangjie-chen/CE7454_2020
This notebook can be used as an example on how to make the preprocessing of climate data for a simulation with OGGM (e.g. from a GCM simulation) computationally significantly faster (in the order of 85% recuction in the computation time). In order to do this 3 steps need to be taken. Of those steps the first two are be...
import pandas as pd import salem import numpy as np import xarray as xr
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
Here a table with all the glaciers globally is being opened and all columns that are not of relevance are being dropped. Collumns to save the coordinates of intrest are being added.
fp = '~/rgi62_allglaciers_stats.h5' # 'https://cluster.klima.uni-bremen.de/~oggm/rgi/rgi62_stats.h5' df = pd.read_hdf(fp) df = df.drop(columns=['GLIMSId', 'BgnDate', 'EndDate', 'O1Region', 'O2Region', 'Zmin', 'Zmax', 'Form', 'Surging', 'Linkages', 'TermType', 'Area', 'Zmed', 'Slope', 'Name', 'Lmax', '...
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
Here the climate dataset of intrest is being opened.
cesm = '~/b.e11.BLMTRC5CN.f19_g16.001.cam.h0.TREFHT.085001-200512.nc' dsd = xr.open_dataset(cesm)
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
Here just the first time step of the file is being selected to make the proccess faster. (For now we're only intrested in the coordinates of the data.)
dsd = dsd.TREFHT[0]
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
This is a loop over all the glaciers of intrest and selects the nearest coordinate in the climate data set. There might be adifference in the longitude values being used between the datasets (-180 to 180 vs 0 to 360). Keep in mind that that you might need to correct for a such a difference.
for gl in np.arange(len(df)): lat = df['CenLat'][gl] lon = df['CenLon'][gl] + 360 cesm_lat = dsd.sel(lat=lat, lon=lon, method='nearest').lat.values cesm_lon = dsd.sel(lat=lat, lon=lon, method='nearest').lon.values df['cesm_lat'][gl] = cesm_lat df['cesm_lon'][gl] = cesm_lon
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
It might be usefull to save the table for later.
df.to_hdf('look_up_table.hdf', key='df')
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
However for we don´t need the full table. Especially when having a climate file with a course resolution, there can like in this case be many duplicates. Therefore the duplicates are being removed.
df_list = df.drop_duplicates(subset=['cesm_lat', 'cesm_lon'], keep='first') df_list = df_list.dropna()
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
Here the climate file of intrest is being opened again. For each coordinate of intrest one file is being generated and saved with the round coordinate in it file name.
dsd = xr.open_dataset(cesm) for ki in np.arange(len(df_list)): ds = dsd.sel(lat=df_list.iloc[ki].cesm_lat, lon=df_list.iloc[ki].cesm_lon, method='nearest') ds.to_netcdf(path='temp_files/b.e11.BLMTRC5CN.f19_g16.001.cam.h0.temp.085001-200512.' + str(round(df_list.iloc[ki].cesm_lat)) + '_' ...
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
The next step would be to create or look up a function that prepares your data so it can be fed for each glacier of interrest to for instance the process_gcm_data. Examples of functions that do so are process_cesm_data and process_cmip5_data. However those functions select that for you from a large file. That part of t...
lookupt = pd.read_hdf(look_up_table) # open the lookup table cesm_lon = str(int(round(lookupt.loc[str(gdir.rgi_id)].cesm_lon))) # select coordinate as in the title of the file cesm_lat = str(int(round(lookupt.loc[str(gdir.rgi_id)].cesm_lat))) # fill the gaps in the title of the file e.g.: # fpath_temp = 'temp_files/b....
_____no_output_____
BSD-3-Clause
Create_climate_files_for_coordinates_of_intrest.ipynb
bearecinos/oggm-shop-notebooks
Load libraries
import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.colors import ListedColormap import cv2 import glob
_____no_output_____
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction
Function
dataset = np.load('../../r-scripts/getting-data-current/data-sets/x_train.npy') def get_sum_heatmap_from_files(data_name, layer, verbose = True, dataset = dataset): npy_loading_pattern = "results/all_matrices_" + data_name + "_" + layer + "*.npy" data_loading_path = glob.glob(npy_loading_pattern) if ve...
_____no_output_____
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction
Get heatmaps
x_train_sum_heatmap = get_sum_heatmap_from_files("x_train", "conv1d_4") x_val_sum_heatmap = get_sum_heatmap_from_files("x_val", "conv1d_4") x_test_sum_heatmap = get_sum_heatmap_from_files("x_test", "conv1d_4")
Loading x_test data from 6 files... Loaded 150 data samples
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction
Plot of training data
# Plot all of the plot_heatmap(x_train_sum_heatmap, x_train_sum_heatmap.shape[0], x_train_sum_heatmap.shape[1]) plot_heatmap(x_train_sum_heatmap, 0, 500) plot_heatmap(x_train_sum_heatmap, 0, 100)
_____no_output_____
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction
Plot of validation data
# Plot all of the entire data plot_heatmap(x_val_sum_heatmap ,x_val_sum_heatmap.shape[0], x_val_sum_heatmap.shape[1]) plot_heatmap(x_val_sum_heatmap, 0, 100)
_____no_output_____
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction
Plot of test data
# Plot all of the entire data plot_heatmap(x_test_sum_heatmap ,x_test_sum_heatmap.shape[0], x_test_sum_heatmap.shape[1]) plot_heatmap(x_test_sum_heatmap, 0, 100)
_____no_output_____
MIT
scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb
TeamMacLean/ruth-effectors-prediction