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
COUNTY HEALTH DEPARTMANT DATASETS
#HEALTH DEPARTMENTS DATA flData=pd.read_csv('https://opendata.arcgis.com/datasets/222c9d85e93540dba523939cfb718d76_0.csv?outSR=%7B%22latestWkid%22%3A4326%2C%22wkid%22%3A4326%7D') flData.to_csv('../_data/Data_Sources/Fl-Data.csv') miData=pd.read_excel('https://www.michigan.gov/documents/coronavirus/Covid-19_Tests_by_Co...
_____no_output_____
Apache-2.0
_notebooks/Matrix Data Scrapper.ipynb
lalalaNomNomNom/Notebooks
COVID TRACKER DATA
#COVID TRACKER DATA da1=pd.read_html('https://covidtracking.com/data/state/alabama') da1[1].to_csv('../_data/Data_Sources/CovidTracker/Alabama.csv') da2=pd.read_html('https://covidtracking.com/data/state/alaska') da2[1].to_csv('../_data/Data_Sources/CovidTracker/Alaska.csv') da3=pd.read_html('https://covidtracking.c...
_____no_output_____
Apache-2.0
_notebooks/Matrix Data Scrapper.ipynb
lalalaNomNomNom/Notebooks
NEW YORK TIMES DATA
#NEW YORK TIMES DATA MASK_NYT=pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/mask-use/mask-use-by-county.csv') MASK_NYT.to_csv('../_data/data_sources/NYT/MASKUSAGE-'+date+'.csv') CASESDEATHSC_NYT=pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv') ...
_____no_output_____
Apache-2.0
_notebooks/Matrix Data Scrapper.ipynb
lalalaNomNomNom/Notebooks
linlab
LINLAB=pd.read_csv('https://raw.githubusercontent.com/lin-lab/COVID19-Viz/master/clean_data/rt_table_export.csv') LINLAB.to_csv('../data/sources/LINLAB/'+date+'-RTCOUNTYLEVEL.csv') wew=requests.get('https://www.geonames.org/statistics/') us=pd.read_html(wew.text) us[1].to_csv('../_data/data_sources/worldCountryPopulati...
_____no_output_____
Apache-2.0
_notebooks/Matrix Data Scrapper.ipynb
lalalaNomNomNom/Notebooks
# MIT License # Copyright (c) 2019. # Project Name: ANLP # File name: code.py # Last modification date: 2/28/19 2:32 PM # Author: ramaseshan # Email:ramaseshanr@yahoo.com # /TTR.py # import nltk from nltk.corpus import stopwords #get the stop words for English stop_words = set(stopwords.words('english')) word...
3826 7079 Number of tokens, Vocabulary, Type-token ratio (Bryant stories) = 15000 2796 0.1864 Number of tokens, Vocabulary, Type-token ratio (Jane Austen Emma) = 15000 3274 0.21826666666666666
MIT
TTR.ipynb
Mukesh7197/anlp-1
Import all libraries
import requests import json import time import multiprocessing import psycopg2
_____no_output_____
MIT
bitcoin_script_load_data_postgres.ipynb
himanshudce/Realtime-Database-with-Firebase
Functions for loading the data and counting rows in meanwhile
# Postgres def load_data_postgres(data): start = time.time() for line in data: response_insert = requests.post('http://localhost:3001/postgres/write/crypto',json=line).text end = time.time() print("postgres",end-start) # Firebase def load_data_firebase(data): start = time.time() prev_ti...
_____no_output_____
MIT
bitcoin_script_load_data_postgres.ipynb
himanshudce/Realtime-Database-with-Firebase
Select which data to load
# # BITCOIN DATA # json_file_path= './data/bitcoin_data_sample.json' # with open(json_file_path) as json_file: # bitcoin_data = json.load(json_file) # # ETHEREUM DATA # json_file_path= 'data/trajectory_data_60k.json' # with open(json_file_path) as json_file: # ethereum_data = json.load(json_file) # # LITECOIN D...
_____no_output_____
MIT
bitcoin_script_load_data_postgres.ipynb
himanshudce/Realtime-Database-with-Firebase
Run process for Firebase
p1 = multiprocessing.Process(target=load_data_postgres, args=(bitcoin_data, )) p2 = multiprocessing.Process(target=load_data_postgres, args=(bitcoin_data, )) p3 = multiprocessing.Process(target=load_data_postgres, args=(bitcoin_data, )) p4 = multiprocessing.Process(target=time_measurement, args=(len(bitcoin_data), )) ...
_____no_output_____
MIT
bitcoin_script_load_data_postgres.ipynb
himanshudce/Realtime-Database-with-Firebase
Run process for PostgreSQL
load_data_postgres(data) # BITCOIN DATA json_file_path= './data/trajectory_data_60k.json' with open(json_file_path) as json_file: data = json.load(json_file) len(data) sql = """insert into trajectory_path(path_info) values(%s)""" sql_count = """select count(*) from trajectory_path""" start_time = time.ti...
1637452712.3010046 2058 4605 7130 9652 12216 14725 17256 19806 22350 24918 27493 30004 32538 35064 37589 40129 42657 45291 47736 50190 52728 missile CONTEXT: PL/pgSQL function process_dist_calculation() line 4 at RAISE 21.097785234451294 current transaction is aborted, commands ignored until end of transaction block ...
MIT
bitcoin_script_load_data_postgres.ipynb
himanshudce/Realtime-Database-with-Firebase
PCA Reduction
from sklearn.decomposition import PCA pca = PCA(n_components=0.99) x_train_pca = pca.fit_transform(x_train) x_valid_pca = pca.transform(x_valid) def plot_faces(faces, label, n_rows = 4, n_cols = 5): plt.figure(figsize=(8, 5)) for index, (face, label) in enumerate(zip(faces, label)): plt.subplot(n_rows...
_____no_output_____
MIT
exercise/chap_9/13_reconstruction_error.ipynb
vaibhavkumar11/hands-on-ml
Modifying Images
from scipy import ndimage # rotated, flipped and darkened the images # flipping and darkening has been used from solution as turned out to be easier x_transformed = [] for face in x_train[:20]: transform = ndimage.rotate(face.reshape(64, 64), angle=np.random.choice([90, 180]), ...
_____no_output_____
MIT
exercise/chap_9/13_reconstruction_error.ipynb
vaibhavkumar11/hands-on-ml
The reconstruction error is not large
plot_faces(x_transformed, y_train[:20]) x_transformed_pca = pca.transform(x_transformed.reshape(-1, 4096)) plot_faces(pca.inverse_transform(x_transformed_pca), y_train[:20])
_____no_output_____
MIT
exercise/chap_9/13_reconstruction_error.ipynb
vaibhavkumar11/hands-on-ml
Creating Extensions Using numpy and scipy=========================================**Author**: `Adam Paszke `_**Updated by**: `Adam Dziedzic `_In this tutorial, we shall go through two tasks:1. Create a neural network layer with no parameters. - This calls into **numpy** as part of its implementation2. Create a neur...
import torch from torch.autograd import Function
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Parameter-less example----------------------This layer doesn’t particularly do anything useful or mathematicallycorrect.It is aptly named BadFFTFunction**Layer Implementation**
from numpy.fft import rfft2, irfft2 class BadFFTFunction(Function): @staticmethod def forward(ctx, input): numpy_input = input.detach().numpy() result = abs(rfft2(numpy_input)) return input.new(result) @staticmethod def backward(ctx, grad_output): numpy_go = grad_outpu...
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
**Example usage of the created layer:**
input = torch.randn(8, 8, requires_grad=True) result = incorrect_fft(input) print(result) result.backward(torch.randn(result.size())) print(input)
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Parametrized example--------------------In deep learning literature, this layer is confusingly referredto as convolution while the actual operation is cross-correlation(the only difference is that filter is flipped for convolution,which is not the case for cross-correlation).Implementation of a layer with learnable wei...
from numpy import flip import numpy as np from scipy.signal import convolve2d, correlate2d from torch.nn.modules.module import Module from torch.nn.parameter import Parameter class ScipyConv2dFunction(Function): @staticmethod def forward(ctx, input, filter, bias): # detach so we can cast to NumPy ...
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
**Example usage:**
module = ScipyConv2d(3, 3) print("Filter and bias: ", list(module.parameters())) input = torch.randn(10, 10, requires_grad=True) output = module(input) print("Output from the convolution: ", output) output.backward(torch.randn(8, 8)) print("Gradient for the input map: ", input.grad)
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
**Check the gradients:**
from torch.autograd.gradcheck import gradcheck moduleConv = ScipyConv2d(3, 3) input = [torch.randn(20, 20, dtype=torch.double, requires_grad=True)] test = gradcheck(moduleConv, input, eps=1e-6, atol=1e-4) print("Are the gradients correct: ", test)
_____no_output_____
BSD-3-Clause
docs/_downloads/52d4aaa33601a2b3990ace6aa45546ce/numpy_extensions_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License");
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
TensorFlow 2.0 での tf.function と AutoGraph View on TensorFlow.org Run in Google Colab View source on GitHub Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意...
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np !pip install tensorflow==2.0.0-beta1 import tensorflow as tf
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
`tf.function` デコレータ`tf.function`を用いてある関数にアノテーションを付けたとしても、一般の関数と変わらずに呼び出せます。一方、実行時にはその関数はグラフへとコンパイルされます。これにより、より高速な実行や、 GPU や TPU での実行、SavedModel へのエクスポートといった利点が得られます。
@tf.function def simple_nn_layer(x, y): return tf.nn.relu(tf.matmul(x, y)) x = tf.random.uniform((3, 3)) y = tf.random.uniform((3, 3)) simple_nn_layer(x, y)
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
アノテーションの結果を調べてみると、 TensorFlow ランタイムとのやり取りのすべてを処理する特別な呼び出し可能オブジェクトを確認できます。
simple_nn_layer
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
記述したコードで複数の関数を利用していたとしても、すべての関数にアノテーションを付ける必要はありません。アノテーションをつけた関数から呼び出されるすべての関数は、グラフモードで実行されます。
def linear_layer(x): return 2 * x + 1 @tf.function def deep_net(x): return tf.nn.relu(linear_layer(x)) deep_net(tf.constant((1, 2, 3)))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
グラフが大量の軽量な演算から構成される場合、関数は Eager Execution で実行するコードよりも高速になる場合があります。しかし、 graph が少量の (畳み込み演算のような) 計算に時間のかかる演算からなる場合、高速化はそれほど見込めないでしょう。
import timeit conv_layer = tf.keras.layers.Conv2D(100, 3) @tf.function def conv_fn(image): return conv_layer(image) image = tf.zeros([1, 200, 200, 100]) # warm up conv_layer(image); conv_fn(image) print("Eager conv:", timeit.timeit(lambda: conv_layer(image), number=10)) print("Function conv:", timeit.timeit(lambda:...
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
Python の制御フローの利用`tf.function`の内部でデータに依存した制御フローを用いる場合、Pythonの制御フロー構文を用いることができます。AutoGraph はそれらの構文を TensorFlow の Ops に書き換えます。たとえば、 `Tensor` に依存する `if` 文は、`tf.cond()` に変換されます。次の例では `x` は `Tensor` です。ですが、 `if` 文は期待するどおりに動作しています。
@tf.function def square_if_positive(x): if x > 0: x = x * x else: x = 0 return x print('square_if_positive(2) = {}'.format(square_if_positive(tf.constant(2)))) print('square_if_positive(-2) = {}'.format(square_if_positive(tf.constant(-2))))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
Note: この例ではスカラー値を用いた単純な条件を用いています。実利用する場合、典型的にはバッチ処理が用いられます。 AutoGraph は `while`, `for`, `if`, `break`, `continue`, `return` といった典型的なPythonの構文をサポートしています。また、これらを入れ子にして利用する場合もサポートしています。つまり、`Tensor`を返す式を`while` 文や `if` 文の条件式として用いることが可能です。また、`for` 文で `Tensor` の要素に渡って反復することも可能です。
@tf.function def sum_even(items): s = 0 for c in items: if c % 2 > 0: print(c) continue s += c return s sum_even(tf.constant([10, 12, 15, 20]))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
より高度な使い方をするユーザーのために、AutoGraph は低レベルAPIも提供しています。次の例では AutoGraph が生成したコードを確認できます。
print(tf.autograph.to_code(sum_even.python_function))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
次はより複雑な制御フローの例です。
@tf.function def fizzbuzz(n): msg = tf.constant('') for i in tf.range(n): if tf.equal(i % 3, 0): tf.print('Fizz') elif tf.equal(i % 5, 0): tf.print('Buzz') else: tf.print(i) fizzbuzz(tf.constant(15))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
Keras での AutoGraph の利用`tf.function` はオブジェクトのメソッドに対しても利用できます。たとえば、カスタムしたKeras モデルにデコレーターを適用できます、典型的には `call` 関数にアノテーションを付けることで実現できるでしょう。より詳細が必要な場合、`tf.keras` を確認してください。
class CustomModel(tf.keras.models.Model): @tf.function def call(self, input_data): if tf.reduce_mean(input_data) > 0: return input_data else: return input_data // 2 model = CustomModel() model(tf.constant([-2, -4]))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
副作用Eager モードのように、通常の場合 `tf.function` の中で、`tf.assign` や `tf.print` といった副作用のある命令を実行できます。また、実行時の順序を保つために、処理順について必要な依存関係を書き加えます。
v = tf.Variable(5) @tf.function def find_next_odd(): v.assign(v + 1) if tf.equal(v % 2, 0): v.assign(v + 1) find_next_odd() v
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
例: シンプルなモデルの学習AutoGraph はこれまで見てきたよりもずっと多くの演算を TensorFlow の内部で実行できます。たとえば、学習のためのループ処理は単に制御フローなので、実際にそれを TensorFlow に持ち込んで処理できます。 データのダウンロード
def prepare_mnist_features_and_labels(x, y): x = tf.cast(x, tf.float32) / 255.0 y = tf.cast(y, tf.int64) return x, y def mnist_dataset(): (x, y), _ = tf.keras.datasets.mnist.load_data() ds = tf.data.Dataset.from_tensor_slices((x, y)) ds = ds.map(prepare_mnist_features_and_labels) ds = ds.take(20000).shuf...
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
モデルの定義
model = tf.keras.Sequential(( tf.keras.layers.Reshape(target_shape=(28 * 28,), input_shape=(28, 28)), tf.keras.layers.Dense(100, activation='relu'), tf.keras.layers.Dense(100, activation='relu'), tf.keras.layers.Dense(10))) model.build() optimizer = tf.keras.optimizers.Adam()
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
学習のためのループ処理の定義
compute_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) compute_accuracy = tf.keras.metrics.SparseCategoricalAccuracy() def train_one_step(model, optimizer, x, y): with tf.GradientTape() as tape: logits = model(x) loss = compute_loss(y, logits) grads = tape.gradient(loss, model.tr...
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
バッチ処理実際のアプリケーションにおいて、処理をバッチにまとめることはパフォーマンスの観点から重要です。AutoGraphを用いるのにもっとも適しているコードは、制御フローを _バッチ_ の単位で決定するようなコードです。もし、個々の _要素_ の単位で制御を決定する場合、パフォーマンスを保つために batch API を試してみてください。一例として、次の Python コードががあったとします。
def square_if_positive(x): return [i ** 2 if i > 0 else i for i in x] square_if_positive(range(-5, 5))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
TensorFlowに同等の処理を行わせる場合、次のように記述したくなるかもしれません。 (これは実際には動作します!)
@tf.function def square_if_positive_naive(x): result = tf.TensorArray(tf.int32, size=x.shape[0]) for i in tf.range(x.shape[0]): if x[i] > 0: result = result.write(i, x[i] ** 2) else: result = result.write(i, x[i]) return result.stack() square_if_positive_naive(tf.range(-5, 5))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
しかし、この場合、次のように書くこともできます。
def square_if_positive_vectorized(x): return tf.where(x > 0, x ** 2, x) square_if_positive_vectorized(tf.range(-5, 5))
_____no_output_____
Apache-2.0
site/ja/beta/guide/autograph.ipynb
abviv/docs
SageMaker Pipelines to Train a BERT-Based Text ClassifierIn this lab, we will do the following:* Define a set of Workflow Parameters that can be used to parametrize a Workflow Pipeline* Define a Processing step that performs cleaning and feature engineering, splitting the input data into train and test data sets* Defi...
%%html <p><b>Shutting down your kernel for this notebook to release resources.</b></p> <button class="sm-command-button" data-commandlinker-command="kernelmenu:shutdown" style="display:none;">Shutdown Kernel</button> <script> try { els = document.getElementsByClassName("sm-command-button"); els[0].click(); } ...
_____no_output_____
Apache-2.0
10_pipeline/00_Overview.ipynb
MarcusFra/workshop
---
root = '/network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/ECMWF_files/raw/' f = 'aquaDay_errorGTE03K_04km_2019-01-01.tif' sat_xr = xr.open_rasterio(root+f) #load the temperature data array sat_xr = sat_xr.rename({'x':'longitude','y':'latitude'}) time_delta = pd.to_timedelta(sat_xr.longitude.data/15,unit='H') fi...
_____no_output_____
MIT
notebooks/legacy/legacy/07. Check MC logic.ipynb
tomkimpson/ML4L
!ls !ls -l # 자세히 보기 !pwd !ls -l ./sample_data # 디렉토리 내용물 자세히 보기 !ls -l ./Wholesale_customers_data.csv import pandas as pd df = pd.read_excel('./wholesale.xls') # y가 없는 데이터 불러와서 y 생성 후 붙이기 df.info() df.head(5) Y = df['label'] X = df.iloc[:,1:9] Y.shape , X.shape from sklearn.tree import DecisionTreeClassifier dtree = ...
_____no_output_____
Apache-2.0
wholesale_decisionTree_classification.ipynb
Ethan-Jeong/test_machinelearning
Question break downin this code we will create a child class in which access parent class creat a class "student"following parameter"i. Nameii. Batch Noiii. Address" creat new child class "DevnationStudents"1.in which we will call parent class const save "course""marks" list as empty2.Add only those courses in the...
class Student: def __init__(self,name,batch_no,address): self.name = name self.batch_no = batch_no self.address = address def set_name(self): return self.name def set_batch_no(self): return self.batch_no def set_adress(self): return self.address ...
_____no_output_____
Apache-2.0
2021_07_15/lab three.ipynb
kashaf874/lab_one
GradientBoostingRegressor with MinMaxScaler This Code template is for regression analysis using a simple GradientBoostingRegressor based on the Gradient Boosting Ensemble Learning Technique using MinMaxScalerfor Feature Rescaling. Required Packages
import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as se from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import r2_score, mean_a...
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
InitializationFilepath of CSV file
#filepath file_path = ""
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
List of features which are required for model training .
#x_values features=[]
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Target feature for prediction.
#y_value target = ''
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.
df=pd.read_csv(file_path) df.head()
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to...
X = df[features] Y = df[target]
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da...
def NullClearner(df): if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])): df.fillna(df.mean(),inplace=True) return df elif(isinstance(df, pd.Series)): df.fillna(df.mode()[0],inplace=True) return df else:return df def EncodeX(df): return pd.get_du...
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Calling preprocessing functions on the feature and target set.
x=X.columns.to_list() for i in x: X[i]=NullClearner(X[i]) X=EncodeX(X) Y=NullClearner(Y) X.head()
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.
f,ax = plt.subplots(figsize=(18, 18)) matrix = np.triu(X.corr()) se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix) plt.show()
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th...
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 123)#performing datasplitting
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Data RescalingMinMaxScaler subtracts the minimum value in the feature and then divides by the range, where range is the difference between the original maximum and original minimum.We will fit an object of MinMaxScaler to train data then transform the same data via fit_transform(X_train) method, following which we wil...
minmax_scaler = MinMaxScaler() X_train = minmax_scaler.fit_transform(X_train) X_test = minmax_scaler.transform(X_test)
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
ModelGradient Boosting builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage a regression tree is fit on the negative gradient of the given loss function. Model Tuning Parameters 1. loss : {‘ls’, ‘lad’, ‘huber’, ‘quantile’}...
# Build Model here model = GradientBoostingRegressor(random_state = 123) model.fit(X_train, y_train)
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.> **score**: The **score** function returns the coefficient of determination R2 of the prediction.
print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100))
Accuracy score 94.47 %
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) b...
y_pred=model.predict(X_test) print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100)) print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred))) print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred)))
R2 Score: 94.47 % Mean Absolute Error 3.02 Mean Squared Error 16.01
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Feature ImportancesThe Feature importance refers to techniques that assign a score to features based on how useful they are for making the prediction.
plt.figure(figsize=(8,6)) n_features = len(X.columns) plt.barh(range(n_features), model.feature_importances_, align='center') plt.yticks(np.arange(n_features), X.columns) plt.xlabel("Feature importance") plt.ylabel("Feature") plt.ylim(-1, n_features)
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.
plt.figure(figsize=(14,10)) plt.plot(range(20),y_test[0:20], color = "blue") plt.plot(range(20),model.predict(X_test[0:20]), color = "red") plt.legend(["Actual","prediction"]) plt.title("Predicted vs True Value") plt.xlabel("Record number") plt.ylabel(target) plt.show()
_____no_output_____
Apache-2.0
Regression/Gradient Boosting Machine/GradientBoostingRegressor_MinMaxScaler.ipynb
surya2365/ds-seed
Plagiarism Text DataIn this project, you will be tasked with building a plagiarism detector that examines a text file and performs binary classification; labeling that file as either plagiarized or not, depending on how similar the text file is when compared to a provided source text. The first step in working with an...
!wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c4147f9_data/data.zip !unzip data # import libraries import pandas as pd import numpy as np import os
_____no_output_____
MIT
Project_Plagiarism_Detection/.ipynb_checkpoints/1_Data_Exploration-checkpoint.ipynb
iahsanujunda/ml_sagemaker_studies
This plagiarism dataset is made of multiple text files; each of these files has characteristics that are is summarized in a `.csv` file named `file_information.csv`, which we can read in using `pandas`.
csv_file = 'data/file_information.csv' plagiarism_df = pd.read_csv(csv_file) # print out the first few rows of data info plagiarism_df.head(10)
_____no_output_____
MIT
Project_Plagiarism_Detection/.ipynb_checkpoints/1_Data_Exploration-checkpoint.ipynb
iahsanujunda/ml_sagemaker_studies
Types of PlagiarismEach text file is associated with one **Task** (task A-E) and one **Category** of plagiarism, which you can see in the above DataFrame. Five task types, A-EEach text file contains an answer to one short question; these questions are labeled as tasks A-E.* Each task, A-E, is about a topic that might...
# print out some stats about the data print('Number of files: ', plagiarism_df.shape[0]) # .shape[0] gives the rows # .unique() gives unique items in a specified column print('Number of unique tasks/question types (A-E): ', (len(plagiarism_df['Task'].unique()))) print('Unique plagiarism categories: ', (plagiarism_df[...
Number of files: 100 Number of unique tasks/question types (A-E): 5 Unique plagiarism categories: ['non' 'cut' 'light' 'heavy' 'orig']
MIT
Project_Plagiarism_Detection/.ipynb_checkpoints/1_Data_Exploration-checkpoint.ipynb
iahsanujunda/ml_sagemaker_studies
You should see the number of text files in the dataset as well as some characteristics about the `Task` and `Category` columns. **Note that the file count of 100 *includes* the 5 _original_ wikipedia files for tasks A-E.** If you take a look at the files in the `data` directory, you'll notice that the original, source ...
# Show counts by different tasks and amounts of plagiarism # group and count by task counts_per_task=plagiarism_df.groupby(['Task']).size().reset_index(name="Counts") print("\nTask:") display(counts_per_task) # group by plagiarism level counts_per_category=plagiarism_df.groupby(['Category']).size().reset_index(name="...
Task:
MIT
Project_Plagiarism_Detection/.ipynb_checkpoints/1_Data_Exploration-checkpoint.ipynb
iahsanujunda/ml_sagemaker_studies
It may also be helpful to look at this last DataFrame, graphically.Below, you can see that the counts follow a pattern broken down by task. Each task has one source text (original) and the highest number on `non` plagiarized cases.
import matplotlib.pyplot as plt % matplotlib inline # counts group = ['Task', 'Category'] counts = plagiarism_df.groupby(group).size().reset_index(name="Counts") plt.figure(figsize=(8,5)) plt.bar(range(len(counts)), counts['Counts'], color = 'blue')
UsageError: Line magic function `%` not found.
MIT
Project_Plagiarism_Detection/.ipynb_checkpoints/1_Data_Exploration-checkpoint.ipynb
iahsanujunda/ml_sagemaker_studies
说明: 给你一个大小为 m * n 的方阵 mat,方阵由若干军人和平民组成,分别用 1 和 0 表示。 请你返回方阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。 如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j,那么我们认为第 i 行的战斗力比第 j 行弱。 军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。示例 1: 输入:mat = [[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0], [1,1,1,1,1]], ...
class Solution: def kWeakestRows(self, mat, k): rows, cols = len(mat), len(mat[0]) powers = {} for i in range(rows): sum_pow = self.count_power(mat[i]) powers[i] = sum_pow print(powers) res = [] powers = sorted(powers.items(), key = lambda x: x...
{0: 5, 1: 1, 2: 2, 3: 4, 4: 5}
Apache-2.0
Binary Search/1015/1337. The K Weakest Rows in a Matrix.ipynb
YuHe0108/Leetcode
New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-pl...
import plotly plotly.__version__
_____no_output_____
CC-BY-3.0
_posts/python-v3/basic/table/table_sub.ipynb
bmb804/documentation
Import CSV Data
import pandas as pd import re import plotly.plotly as py import plotly.graph_objs as go df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/Mining-BTC-180.csv') # remove min:sec:millisec from dates for i, row in enumerate(df['Date']): p = re.compile(' 00:00:00') datetime = p.split(df[...
_____no_output_____
CC-BY-3.0
_posts/python-v3/basic/table/table_sub.ipynb
bmb804/documentation
Table and Right Aligned PlotsIn Plotly there is no native way to insert a Plotly Table into a Subplot. To do this, create your own `Layout` object and defining multiple `xaxis` and `yaxis` to split up the chart area into different domains. Then for the traces you wish to insert in your final chart, set their `xaxis` a...
import plotly.plotly as py import plotly.graph_objs as go table_trace1 = go.Table( domain=dict(x=[0, 0.5], y=[0, 1.0]), columnwidth = [30] + [33, 35, 33], columnorder=[0, 1, 2, 3, 4], header = dict(height = 50, values = [['<b>Date</b>'],['<b>Number<br>transactions</b>'...
_____no_output_____
CC-BY-3.0
_posts/python-v3/basic/table/table_sub.ipynb
bmb804/documentation
Vertical Table and Graph Subplot
import plotly.plotly as py import plotly.graph_objs as go table_trace2 = go.Table( domain=dict(x=[0, 1], y=[0, 1.0]), columnwidth = [30] + [33, 35, 33], columnorder=[0, 1, 2, 3, 4], header = dict(height = 50, values = [['<b>Date</b>'],['<b>Hash Rate, TH/sec</b>'], ...
_____no_output_____
CC-BY-3.0
_posts/python-v3/basic/table/table_sub.ipynb
bmb804/documentation
ReferenceSee https://plot.ly/python/reference/table for more information regarding chart attributes! For examples of Plotly Tables, see: https://plot.ly/python/table/
from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-not...
_____no_output_____
CC-BY-3.0
_posts/python-v3/basic/table/table_sub.ipynb
bmb804/documentation
Name: Anjum Rohra Overview![it_sector-2.jpg](attachment:it_sector-2.jpg)Being a popular finance journalist of Europe, everyone is waiting for the IT Salary Survey report you release every 3 years. The IT Sector is booming and the younger aspirants keep themselves updated with the trends by the beautiful visualization...
import plotly.express as px import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, Input
_____no_output_____
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
Importing data
data_18 = pd.read_csv('Survey_2018.csv') data_19 = pd.read_csv('Survey_2019.csv') data_20 = pd.read_csv('Survey_2020.csv')
_____no_output_____
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
Imputing the missing values 2020 imputation
data_20 = data_20.rename(columns = {'Position ': 'Position'}) data_20.isnull().sum() data_20['Age'].fillna(data_20['Age'].mean(), inplace=True) data_20['Gender'].fillna('Male', inplace=True) data_20['Position'].fillna('Software Engineer', inplace=True) data_20['Position'].replace({'Account Managet': 'Account Manager', ...
_____no_output_____
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
2018 imputation
data_18.isnull().sum() data_18['Gender'].fillna('M', inplace=True) data_18['City'].fillna('Berlin', inplace=True) data_18['Position'].fillna('Java Developer', inplace=True) data_18['Your level'].fillna('Senior', inplace=True) data_18['Are you getting any Stock Options?'].fillna('No', inplace=True) data_18['Main languag...
_____no_output_____
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
2019 imputation
data_19.drop('0',axis=1,inplace=True) data_19.isnull().sum() data_19['Seniority level'].fillna('Senior', inplace=True) data_19['Position (without seniority)'].fillna('Backend Developer', inplace=True) data_19['Your main technology / programming language'].fillna('Python', inplace=True) data_19['Main language at work']....
_____no_output_____
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
Data Visualization with Dash Application
app = dash.Dash(__name__) app.layout = html.Div([ html.Div([ dcc.Dropdown(id='years', multi=False, clearable=False, options=[{'label':x, 'value':x} for x in sorted(['2018','2019','2020'])], value="2018") ],style={'width':'50%'}), html.Div([ dcc....
Dash is running on http://127.0.0.1:8001/ Dash is running on http://127.0.0.1:8001/ * Serving Flask app "__main__" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off
Apache-2.0
IT_Survey_Application/building_the_dash_application.ipynb
anjumrohra/Data_visualization_with_Plotly_and_Dash
연습문제- 인터파크 투어에서 조회한 결과를 MongoDB로 저장하기 컬렉션 : tour- 필드 : 이미지경로-img, 상세페이지경로-link, 상품명-title, 상품설명-desc, 가격-price headless로 크롬 실행```options = webdriver.ChromeOptions()options.add_argument("headless")options.add_argument("window-size=1920x1080")driver = webdriver.Chrome(executable_path='C:/Code/chromedriver.exe', options...
from selenium import webdriver as wd driver = wd.Chrome(executable_path='C:/Code/chromedriver.exe') from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from pymongo import MongoClient client = M...
_____no_output_____
MIT
database/08_pymongo.ipynb
dayoungMM/TIL
Crypto ArbitrageIn this Challenge, you'll take on the role of an analyst at a high-tech investment firm. The vice president (VP) of your department is considering arbitrage opportunities in Bitcoin and other cryptocurrencies. As Bitcoin trades on markets across the globe, can you capitalize on simultaneous price dislo...
import pandas as pd from pathlib import Path %matplotlib inline
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Collect the DataTo collect the data that you’ll need, complete the following steps:Instructions. 1. Using the Pandas `read_csv` function and the `Path` module, import the data from `bitstamp.csv` file, and create a DataFrame called `bitstamp`. Set the DatetimeIndex as the Timestamp column, and be sure to parse and for...
# Read in the CSV file called "bitstamp.csv" using the Path module. # The CSV file is located in the Resources folder. # Set the index to the column "Date" # Set the parse_dates and infer_datetime_format parameters bitstamp = pd.read_csv( Path("Resources/bitstamp.csv"), index_col = "Timestamp", parse_dates...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 2: Use the `head` (and/or the `tail`) function to confirm that Pandas properly imported the data.
# Use the head (and/or tail) function to confirm that the data was imported properly. # YOUR CODE HERE display(bitstamp.head()) display(bitstamp.tail())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 3: Repeat Steps 1 and 2 for `coinbase.csv` file.
# Read in the CSV file called "coinbase.csv" using the Path module. # The CSV file is located in the Resources folder. # Set the index to the column "Timestamp" # Set the parse_dates and infer_datetime_format parameters coinbase = pd.read_csv( Path("Resources/coinbase.csv"), index_col = "Timestamp", parse_...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Prepare the DataTo prepare and clean your data for analysis, complete the following steps:1. For the bitstamp DataFrame, replace or drop all `NaN`, or missing, values in the DataFrame.2. Use the `str.replace` function to remove the dollar signs ($) from the values in the Close column.3. Convert the data type of the Cl...
# For the bitstamp DataFrame, replace or drop all NaNs or missing values in the DataFrame # Displays the null count display(bitstamp.isnull().sum()) # Uses fillna() to replace all null values with 0 bitstamp = bitstamp.fillna(0) # Verifies nulls have been replaced display(bitstamp.isnull().sum())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 2: Use the `str.replace` function to remove the dollar signs ($) from the values in the Close column.
# Display head to show before $ removed display(bitstamp.head()) # Use the str.replace function to remove the dollar sign, $ bitstamp.loc[:,"Close"] = bitstamp.loc[:,"Close"].str.replace("$","") # Display head to show after has been removed. display(bitstamp.head())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 3: Convert the data type of the Close column to a `float`.
# Convert the Close data type to a float # display type before change display(bitstamp["Close"].dtypes) # change the column type to float bitstamp.loc[:, "Close"] = bitstamp.loc[:, "Close"].astype("float") # display the new type display(bitstamp["Close"].dtypes)
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 4: Review the data for duplicated values, and drop them if necessary.
# Review the data for duplicate values, and drop them if necessary # Count the number of duplicates display(bitstamp.duplicated().sum()) # Drop the duplicates bitstamp = bitstamp.drop_duplicates() # Count the number of duplicates display(bitstamp.duplicated().sum())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 5: Repeat Steps 1–4 for the coinbase DataFrame.
# Step 1 - Remove the Nulls # Displays the null count display(coinbase.isnull().sum()) # Uses fillna() to replace all null values with 0 coinbase = coinbase.fillna(0) # Verifies nulls have been replaced display(coinbase.isnull().sum()) # Step 2 - Remove $ from Close column # Display head to show before $ removed ...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Analyze the DataYour analysis consists of the following tasks: 1. Choose the columns of data on which to focus your analysis.2. Get the summary statistics and plot the data.3. Focus your analysis on specific dates.4. Calculate the arbitrage profits. Step 1: Choose columns of data on which to focus your analysis.Selec...
# Use loc or iloc to select `Timestamp (the index)` and `Close` from bitstamp DataFrame bitstamp_sliced = bitstamp.iloc[:,[3]] # Review the first five rows of the DataFrame bitstamp_sliced.head() # Use loc or iloc to select `Timestamp (the index)` and `Close` from coinbase DataFrame coinbase_sliced = coinbase.iloc[:,[...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 2: Get summary statistics and plot the data.Sort through the time series data associated with the bitstamp and coinbase DataFrames to identify potential arbitrage opportunities. To do so, complete the following steps:1. Generate the summary statistics for each DataFrame by using the `describe` function.2. For eac...
# Generate the summary statistics for the bitstamp DataFrame bitstamp_sliced.describe() # Generate the summary statistics for the coinbase DataFrame coinbase_sliced.describe() # Create a line plot for the bitstamp DataFrame for the full length of time in the dataset # Be sure that the figure size, title, and color ar...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
**Question** Based on the visualizations of the different time periods, has the degree of spread change as time progressed?**Answer** Yes. Early in the timeframe, there were more frequent and more severe divergences between the price of Bitcoin on Bitstamp and Coinbase. Step 3: Focus Your Analysis on Specific DatesFo...
# Create an overlay plot that visualizes the two dataframes over a period of one day early in the dataset. # Be sure that the plots include the parameters `legend`, `figsize`, `title`, `color` and `label` coinbase_sliced["Close"].loc["2018-01-24" : "2018-01-24"].plot(legend = True, figsize=(15, 7), title="Jan. 25, 20...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Step 4: Calculate the Arbitrage ProfitsCalculate the potential profits for each date that you selected in the previous section. Your goal is to determine whether arbitrage opportunities still exist in the Bitcoin market. Complete the following steps:1. For each of the three dates, measure the arbitrage spread between ...
# For the date early in the dataset, measure the arbitrage spread between the two exchanges # by subtracting the lower-priced exchange from the higher-priced one # Determines the arbitrage spread at three different times - early, middle, and late arbitrage_spread_early = bitstamp_sliced['Close'].loc['2018-01-24'] - c...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
2. For each of the three dates, calculate the spread returns. To do so, divide the instances that have a positive arbitrage spread (that is, a spread greater than zero) by the price of Bitcoin from the exchange you’re buying on (that is, the lower-priced exchange). Review the resulting DataFrame.
# For the date early in the dataset, calculate the spread returns by dividing the instances when the arbitrage spread is positive (> 0) # by the price of Bitcoin from the exchange you are buying on (the lower-priced exchange). spread_return_early= spread_return_early_positive / coinbase_sliced['Close'].loc['2018-01-24...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
3. For each of the three dates, narrow down your trading opportunities even further. To do so, determine the number of times your trades with positive returns exceed the 1% minimum threshold that you need to cover your costs.
# For the date early in the dataset, determine the number of times your trades with positive returns # exceed the 1% minimum threshold (.01) that you need to cover your costs profitable_trades_early = spread_return_early[spread_return_early > .01] profitable_trades_middle = spread_return_middle[spread_return_middle > ...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
4. Generate the summary statistics of your spread returns that are greater than 1%. How do the average returns compare among the three dates?
# For the date early in the dataset, generate the summary statistics for the profitable trades # or you trades where the spread returns are are greater than 1% display(profitable_trades_early.describe()) display(profitable_trades_middle.describe()) display(profitable_trades_late.describe())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
5. For each of the three dates, calculate the potential profit, in dollars, per trade. To do so, multiply the spread returns that were greater than 1% by the cost of what was purchased. Make sure to drop any missing values from the resulting DataFrame.
# For the date early in the dataset, calculate the potential profit per trade in dollars # Multiply the profitable trades by the cost of the Bitcoin that was purchased profit_early = spread_return_early[spread_return_early > .01] * coinbase_sliced['Close'].loc['2018-01-24'] profit_middle = spread_return_middle[spread_...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
6. Generate the summary statistics, and plot the results for each of the three DataFrames.
# Generate the summary statistics for the early profit per trade DataFrame display(profit_per_trade_early.describe()) display(profit_per_trade_middle.describe()) display(profit_per_trade_late.describe()) # Plot the results for the early profit per trade DataFrame profit_per_trade_early.plot(legend = True, figsize=(15, ...
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
7. Calculate the potential arbitrage profits that you can make on each day. To do so, sum the elements in the profit_per_trade DataFrame.
# Calculate the sum of the potential profits for the early profit per trade DataFrame display(profit_per_trade_early.sum()) display(profit_per_trade_middle.sum()) display(profit_per_trade_late.sum())
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
8. Using the `cumsum` function, plot the cumulative sum of each of the three DataFrames. Can you identify any patterns or trends in the profits across the three time periods?
# Use the cumsum function to calculate the cumulative profits over time for the early profit per trade DataFrame cumulative_profit_early = profit_per_trade_early.cumsum()# YOUR CODE HERE # Plot the cumulative sum of profits for the early profit per trade DataFrame cumulative_profit_early.plot()
_____no_output_____
MIT
.ipynb_checkpoints/crypto_arbitrage-checkpoint.ipynb
justcb/bitcoin_arb
Design MERFISH probes using the example inputs from Jeff Moffitt. The original MATLAB design pipeline can be found at https://github.com/ZhuangLab/MERFISH_analysis. Prepare inputs
# Download the input data # This is for the UNIX-like operating systems. If you are using Windows, just download the files accordingly. !mkdir temporary_data !wget http://zhuang.harvard.edu/merfish/MERFISHData/MERFISH_Examples2.zip -O temporary_data/MERFISH_Examples2.zip !unzip -o temporary_data/MERFISH_Examples2.zip -...
\\10.245.74.212\Chromatin_NAS_2\Libraries\CTP-10_Aire\MERFISH_designer\MERFISH_Examples2\transcripts.fasta
MIT
Library_design/CTP-10_Aire/Merfish_design_from_XJP.ipynb
shiwei23/Chromatin_Analysis_Scripts
Initialize data structures
# Import the modules import os import sys from IPython.display import display import MERFISH_probe_design import MERFISH_probe_design.IO.file_io as fio import MERFISH_probe_design.probe_design.probe_dict as p_d import MERFISH_probe_design.probe_design.OTTable_dict as ot import MERFISH_probe_design.probe_design.readou...
_____no_output_____
MIT
Library_design/CTP-10_Aire/Merfish_design_from_XJP.ipynb
shiwei23/Chromatin_Analysis_Scripts
load transcriptome
# Load the transcriptome as a pandas data frame transcriptome = fio.load_transcriptome(transcripts_fasta_file, fpkm_tracking_file) # Make sure that the transcriptome data frame has the standard column names. # The standard columns are: transcript_id, sequence, gene_id, gene_short_name and FPKM. # Also remove the non-s...
Load the OTTable from \\10.245.74.212\Chromatin_NAS_2\Libraries\CTP-10_Aire\MERFISH_designer\MERFISH_Examples2\outputs\ottable_transcriptome.pkl. Wall time: 1min 8s
MIT
Library_design/CTP-10_Aire/Merfish_design_from_XJP.ipynb
shiwei23/Chromatin_Analysis_Scripts
Select target regions
# Calculate and plot the GC contents of the target regions filters.calc_gc_for_probe_dict(probe_dict, column_key_seq='target_sequence', column_key_write='target_GC') plot.plot_hist(probe_dict, column_key='target_GC') # Filter GC cotent and plot the GC content after filtering filters.filter_probe_dict_by_metric(probe_di...
VPS13D ENST00000613099.4: 9512 / 9545 probes passed the filter 0.75 < target_specificity < inf. PRDM2 ENST00000343137.8: 2806 / 2863 probes passed the filter 0.75 < target_specificity < inf. LUZP1 ENST00000418342.5: 5478 / 5478 probes passed the filter 0.75 < target_specificity < inf. CNR2 ENST00000374472.4: 249...
MIT
Library_design/CTP-10_Aire/Merfish_design_from_XJP.ipynb
shiwei23/Chromatin_Analysis_Scripts
Design readout sequences
# Load the readout sequences into a data frame readout_seqs = fio.load_fasta_into_df(readout_fasta_file) rs.append_on_bit_ids_to_readout_sequences(readout_seqs, bit_names) readout_seqs # Add the readout sequences. Here we randomly add 3 readout sequences to each probe. # Add an "A" between the concatenated sequences. ...
_____no_output_____
MIT
Library_design/CTP-10_Aire/Merfish_design_from_XJP.ipynb
shiwei23/Chromatin_Analysis_Scripts