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 |
|---|---|---|---|---|---|
Sonar - Decentralized Model Training Simulation (local)DISCLAIMER: This is a proof-of-concept implementation. It does not represent a remotely product ready implementation or follow proper conventions for security, convenience, or scalability. It is part of a broader proof-of-concept demonstrating the vision of the Op... | import warnings
import numpy as np
import phe as paillier
from sonar.contracts import ModelRepository,Model
from syft.he.Paillier import KeyPair
from syft.nn.linear import LinearClassifier
import numpy as np
from sklearn.datasets import load_diabetes
def get_balance(account):
return repo.web3.fromWei(repo.web3.eth... | _____no_output_____ | Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Setting up the Experiment | # for the purpose of the simulation, we're going to split our dataset up amongst
# the relevant simulated users
diabetes = load_diabetes()
y = diabetes.target
X = diabetes.data
validation = (X[0:42],y[0:42])
anonymous_diabetes_users = (X[42:],y[42:])
# we're also going to initialize the model trainer smart contract,... | _____no_output_____ | Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Step 1: Cure Diabetes Inc Initializes a Model and Provides a Bounty | pubkey,prikey = KeyPair().generate(n_length=1024)
diabetes_classifier = LinearClassifier(desc="DiabetesClassifier",n_inputs=10,n_labels=1)
initial_error = diabetes_classifier.evaluate(validation[0],validation[1])
diabetes_classifier.encrypt(pubkey)
diabetes_model = Model(owner=cure_diabetes_inc,
... | _____no_output_____ | Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Step 2: An Anonymous Patient Downloads the Model and Improves It | model_id
model = repo[model_id]
diabetic_address,input_data,target_data = anonymous_diabetics[0]
repo[model_id].submit_gradient(diabetic_address,input_data,target_data) | _____no_output_____ | Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Step 3: Cure Diabetes Inc. Evaluates the Gradient | repo[model_id]
old_balance = get_balance(diabetic_address)
print(old_balance)
new_error = repo[model_id].evaluate_gradient(cure_diabetes_inc,repo[model_id][0],prikey,pubkey,validation[0],validation[1])
new_error
new_balance = get_balance(diabetic_address)
incentive = new_balance - old_balance
print(incentive) | 0.000840812917924814
| Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Step 4: Rinse and Repeat | model
for i,(addr, input, target) in enumerate(anonymous_diabetics):
try:
model = repo[model_id]
# patient is doing this
model.submit_gradient(addr,input,target)
# Cure Diabetes Inc does this
old_balance = get_balance(addr)
new_error = model... | new error = 26580005
incentive = 0.00162
new error = 26639344
incentive = 0.00000
new error = 26536737
incentive = 0.00163
new error = 26546235
incentive = 0.00000
| Apache-2.0 | notebooks/Pre-Hydrogen-Demo.ipynb | jopasserat/PySonar |
Welcome to the [Tensor2Tensor](https://github.com/tensorflow/tensor2tensor) ColabTensor2Tensor, or T2T for short, is a library of deep learning models and datasets designed to make deep learning more accessible and [accelerate ML research](https://research.googleblog.com/2017/06/accelerating-deep-learning-research.htm... | #@title
# Copyright 2018 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License");
# 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... | /home/jk/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
| MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
Download MNIST and inspect it | # A Problem is a dataset together with some fixed pre-processing.
# It could be a translation dataset with a specific tokenization,
# or an image dataset with a specific resolution.
#
# There are many problems available in Tensor2Tensor
problems.available()
# Fetch the MNIST problem
mnist_problem = problems.problem("im... | INFO:tensorflow:Reading data files from /home/jk/t2t/data/image_mnist-train*
INFO:tensorflow:partition: 0 num_data_files: 10
Label: 1
| MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
Translate from English to German with a pre-trained model | # Fetch the problem
ende_problem = problems.problem("translate_ende_wmt32k")
# Copy the vocab file locally so we can encode inputs and decode model outputs
# All vocabs are stored on GCS
vocab_name = "vocab.ende.32768"
vocab_file = os.path.join(gs_data_dir, vocab_name)
!gsutil cp {vocab_file} {data_dir}
# Get the enc... | INFO:tensorflow:Greedy Decoding
Inputs: The animal didn't cross the street because it was too tired
Outputs: Das Tier überquerte nicht die Straße, weil es zu müde war.
| MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
Attention Viz Utils | from tensor2tensor.visualization import attention
from tensor2tensor.data_generators import text_encoder
SIZE = 35
def encode_eval(input_str, output_str):
inputs = tf.reshape(encoders["inputs"].encode(input_str) + [1], [1, -1, 1, 1]) # Make it 3D.
outputs = tf.reshape(encoders["inputs"].encode(output_str) + [1],... | _____no_output_____ | MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
Display Attention | # Convert inputs and outputs to subwords
inp_text = to_tokens(encoders["inputs"].encode(inputs))
out_text = to_tokens(encoders["inputs"].encode(outputs))
# Run eval to collect attention weights
example = encode_eval(inputs, outputs)
with tfe.restore_variables_on_create(tf.train.latest_checkpoint(checkpoint_dir)):
tr... | INFO:tensorflow:Transforming feature 'inputs' with symbol_modality_33708_512.bottom
INFO:tensorflow:Transforming 'targets' with symbol_modality_33708_512.targets_bottom
INFO:tensorflow:Building model body
INFO:tensorflow:Transforming body output with symbol_modality_33708_512.top
| MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
Train a custom model on MNIST | # Create your own model
class MySimpleModel(t2t_model.T2TModel):
def body(self, features):
inputs = features["inputs"]
filters = self.hparams.hidden_size
h1 = tf.layers.conv2d(inputs, filters,
kernel_size=(5, 5), strides=(2, 2))
h2 = tf.layers.conv2d(tf.nn.relu(h1), filters... | INFO:tensorflow:Reading data files from /content/t2t/data/image_mnist-dev*
INFO:tensorflow:partition: 0 num_data_files: 1
accuracy_top5: 0.99
accuracy: 0.97
| MIT | CS20_Tensorflow_for_Deep_learning_Research/Tensor2Tensor_Intro.ipynb | jungi21cc/DeepLearning |
ArcGIS Online の解析機能を使用する 使用するデータ* 栃木県のダム諸元表: https://www.geospatial.jp/ckan/dataset/09000-103 データを確認する | # pandas を使用して csv ファイルの読み込み、中身を表示する
import pandas as pd
dam_csv = pd.read_csv('https://www.geospatial.jp/ckan/dataset/d6a87e42-6e86-449e-9d76-1e40319bb99b/resource/b5d633c8-f2c8-4baa-88a9-fcf1872dcfcd/download/724522014tochiginodamsyogen04033.csv',encoding="SHIFT-JIS")
dam_csv | _____no_output_____ | Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
ArcGIS Online にログイン | # ArcGIS Online に開発者アカウントでサインインする
from arcgis.gis import GIS
import getpass
develoersUser = 'あなたのユーザー名'
develoersPass = getpass.getpass('ユーザー['+ develoersUser + ']のパスワード=')
gis = GIS("http://"+ develoersUser +".maps.arcgis.com/",develoersUser,develoersPass)
user = gis.users.get(develoersUser)
user | ユーザー[ejpythondev]のパスワード=········
| Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
ArcGIS Online にホスト フィーチャ サービスを公開する | # ArcGIS Online に CSV ファイルをアイテムとして追加する
csv_file = 'https://www.geospatial.jp/ckan/dataset/d6a87e42-6e86-449e-9d76-1e40319bb99b/resource/b5d633c8-f2c8-4baa-88a9-fcf1872dcfcd/download/724522014tochiginodamsyogen04033.csv'
csv_item = gis.content.add({}, csv_file)
display(csv_item)
# CSV にある緯度経度の情報を使用して、追加したアイテムからホスト フィーチャ... | _____no_output_____ | Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
ArcGIS Online の集水域解析を実行する | # ダムのポイントのホスト フィーチャ サービスを引数にして集水域の作成ツール(create_watersheds)を実行する
from arcgis.features import analysis
watershedsResult = analysis.create_watersheds(csv_lyr, output_name='watersheds_result')
watershedsResult
# 解析結果の集水域ポリゴンをマップに追加して表示する
map.add_layer(watershedsResult) | _____no_output_____ | Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
ArcGIS Online の下流解析を実行する | # 集水域の解析結果で出力された調整された入力ポイントを引数にして下流解析ツール(trace_downstream)を実行する
input_layer = watershedsResult.layers[0]
downstreamResult = analysis.trace_downstream(input_layer, output_name='downstream_result')
downstreamResult
# 解析結果の河川ラインをマップに追加して表示する
map.add_layer(downstreamResult) | _____no_output_____ | Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
Web マップとして保存する | # Web マップのタイトルなどを定義する
webMap_properties = {'title':'栃木県のダム・河川',
'snippet':'Python API で作成した栃木県のダム・河川 Web マップ',
'tags':'栃木県, ダム, 河川',
'extent':downstreamResult.extent
}
# Web マップを保存する
webMap = map.save(item_properties=webMap_properties)
... | _____no_output_____ | Apache-2.0 | samples/5.analysis.ipynb | EsriJapan/arcgis-samples-python-api |
Some testing and analysis of the new `Snapshot` implementation | from __future__ import print_function
import numpy as np
import openpathsampling as paths
import openpathsampling.engines.features as features | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Function to show the generated source code | from IPython.display import Markdown
def code_to_md(snapshot_class):
md = '```py\n'
for f, s in snapshot_class.__features__.debug.items():
if s is not None:
md += s
else:
md += 'def ' + f + '(...):\n # user defined\n pass'
md += '\n\n'
md += '```'
... | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Check generated source code Generate simple Snapshot without any features using factory | EmptySnap = paths.engines.snapshot.SnapshotFactory('no', [], 'Empty', use_lazy_reversed=False) | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Generate Snapshot with overridden `.copy` method. | @features.base.attach_features([
features.velocities,
features.coordinates,
features.box_vectors,
features.topology
])
class A(paths.BaseSnapshot):
def copy(self):
return 'copy' | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Check that subclassing with overridden copy needs more overriding. | #! lazy
# lazy because of some issue with Py3k comparing strings
try:
@features.base.attach_features([
])
class B(A):
pass
except RuntimeWarning as e:
print(e)
else:
raise RuntimeError('Should have raised a RUNTIME warning')
a = A()
assert(a.copy() == 'copy')
# NBVAL_IGNORE_OUTPUT
Markdo... | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Test subclassing | @features.base.attach_features([
])
class HyperSnap(MegaSnap):
pass | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Test subclassing with redundant features (should work / be ignored) | @features.base.attach_features([
paths.engines.features.statics,
])
class HyperSnap(MegaSnap):
pass | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Test subclassing with conflicting features (should not work) | try:
@features.base.attach_features([
paths.engines.features.statics,
paths.engines.features.coordinates
])
class HyperSnap(MegaSnap):
pass
except RuntimeWarning as e:
print(e)
else:
raise RuntimeError('Should have raised a RUNTIME warning')
# NBVAL_IGNORE_OUTPUT
Markdown... | _____no_output_____ | MIT | examples/tests/test_snapshot.ipynb | bdice/openpathsampling |
Find the Tents_Combinatorial Optimization course, FEE CTU in Prague. Created by [Industrial Informatics Department](http://industrialinformatics.fel.cvut.cz)._The problem was taken from https://www.brainbashers.com/tents.asp ; there, you can try to solve some examples manually. TaskFind all of the hidden tents in the ... | # 2x2 - Extra small (for debugging)
n1 = 3
r1 = (1, 1, 0)
c1 = (1, 0, 1)
trees1 = [(1,1), (3,2)]
# 8x8 - Medium
n2 = 8
r2 = (3, 1, 1, 2, 0, 2, 0, 3)
c2 = (2, 1, 2, 2 ,1, 1 ,2 ,1)
trees2 = [(2, 1), (5, 1), (6, 1),
(1, 2),
(3, 3),
(3, 4), (6, 4),
(4, 5), (6, 5),
(8, 7),
... | _____no_output_____ | MIT | cv06/forest.ipynb | LukasForst/KO |
OutputYou should find the coordinates $(x_i, y_i), i \in \{1,\dots,k\}$, of the individual tents. Model | from gurobipy import *
from itertools import product as cartesian
def optimize(n, r, c, trees):
m = Model()
# n+2 -> extend the board such as we don't need check borders
# this is really nice hack, disable all variables with uper bound 0 and
# then allow them only in tree neighborhood -> we don't need s... | _____no_output_____ | MIT | cv06/forest.ipynb | LukasForst/KO |
Visualization | import matplotlib.pyplot as plt
import numpy as np
def visualize(n, trees, tents, r, c):
grid = [["." for _ in range(n+2)] for _ in range(n+2)]
for t_x, t_y in tents:
grid[t_y][t_x] = "X"
for t_x, t_y in trees:
grid[t_y][t_x] = "T"
print(" ", end="")
for c_cur in c:
... | Gurobi Optimizer version 9.0.1 build v9.0.1rc0 (mac64)
Optimize a model with 520 rows, 484 columns and 4720 nonzeros
Model fingerprint: 0xcc059f6b
Variable types: 0 continuous, 484 integer (484 binary)
Coefficient statistics:
Matrix range [1e+00, 9e+00]
Objective range [0e+00, 0e+00]
Bounds range [1e+00,... | MIT | cv06/forest.ipynb | LukasForst/KO |
GradientBoostingRegressor with Normalize
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 Normalizer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import r2_score, mean_abs... | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path = "" | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/ds-seed |
Target feature for prediction. | #y_value
target = '' | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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_dummies(df) | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/ds-seed |
Data RescalingNormalizer normalizes samples (rows) individually to unit norm.Each sample with at least one non zero component is rescaled independently of other samples so that its norm (l1, l2 or inf) equals one.We will fit an object of Normalizer to train data then transform the same data via fit_transform(X_train) ... | normalizer = Normalizer()
X_train = normalizer.fit_transform(X_train)
X_test = normalizer.transform(X_test) | _____no_output_____ | Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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 93.80 %
| Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/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: 93.80 %
Mean Absolute Error 3.24
Mean Squared Error 17.94
| Apache-2.0 | Regression/Gradient Boosting Machine/GradientBoostingRegressor_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/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_Normalize.ipynb | devVipin01/ds-seed |
Gene Expression Simple DemoThis shows how to query BgeeDb gene expression data ingested in Monarch | ## Create an ontology factory in order to fetch Uberon
from ontobio.ontol_factory import OntologyFactory
ofactory = OntologyFactory()
ont = ofactory.create("uberon")
## Create a sub-ontology that excludes all relations other than is-a and part-of
subont = ont.subontology(relations=['subClassOf', 'BFO:0000050'])
## Cr... | MGI:95590 Ftl2-ps []
MGI:1098641 Wasf2 [('MP:0002188', 'small heart'), ('MP:0020329', 'decreased capillary density'), ('MP:0011091', 'prenatal lethality, complete penetrance'), ('HP:0002170', None), ('HP:0000969', None), ('MP:0003984', 'embryonic growth retardation'), ('MP:0000260', 'abnormal angiogenesis'), ('MP:00110... | BSD-3-Clause | notebooks/Gene_Expression.ipynb | alliance-genome/ontobio |
OverviewAs data scientists working in a cyber-security company, we wanted to show that Natural Language Processing (NLP) algorithms can be applied to security related events. For this task we used 2 algorithm developed by Google: **Word2vec** ([link](https://arxiv.org/abs/1301.3781)) and **Doc2vec** ([link](https://ar... | import random
from IPython.display import display, Markdown, clear_output, HTML
def hide_toggle():
# @author: harshil
# @Source: https://stackoverflow.com/a/28073228/6306692
this_cell = """$('div.cell.code_cell.rendered.selected')"""
next_cell = this_cell + '.next()'
toggle_text = 'Show/hide code' ... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Load CSV data file Ready to use dataset - Customer Complaints- Open source dataset by U.S. gov ([link](https://catalog.data.gov/dataset/consumer-complaint-database))- **Events**: the first word in the column 'issue' - **Label**: the product- **Groupping by**: 'Zip code' | display(hide_toggle())
df = None
def load_csv(btn):
global df
clear_output()
display(hide_toggle())
display(widgets.VBox([filename_input, nrows_input]))
display(HTML('<img src="../loading.gif" alt="Drawing" style="width: 50px;"/>'))
nrows = int(nrows_input.value)
df = pd.read_csv(filename_... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Map columnsThe data should have at least 3 columns:- **Timestamp** (int) - if you don't have timestamps, it can also be a simple increasing index- **Event** (string) - rule name, event description, etc. Must be a single word containing only alpha-numeric characters- **Label** (string) - type of event. This will be lat... | time_column_input, event_column_input, label_column_input = None, None, None
def show_dropdown(obj):
global time_column_input, event_column_input, label_column_input
time_column_input = widgets.Dropdown(options=df.columns, description='Time column:')
event_column_input = widgets.Dropdown(options=df.columns,... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Select additional grouping columnsSelect those columns which represents unique sequences | checkboxes = None
def show_checkboxes(obj):
global checkboxes
checkboxes = {k:widgets.Checkbox(description=k) for k in df.columns if k not in [time_column_input.value,
event_column_input.value,
... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Create sentencesThis cell will group events into sentences (using the grouping columns selected). It will then split sentences if to consecutive events are separated by more than the given timeout (default: 300 seconds) | display(hide_toggle())
dataset_name = os.path.splitext(os.path.basename(filename_input.value))[0]
sentences_df, sentences_filepath = None, None
def sentences(obj):
global sentences_df, sentences_filepath
clear_output()
display(hide_toggle())
display(HTML('<img src="../loading.gif" alt="Drawing" style="... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Prepare dataset1) Train a doc2vec model to extract the embedding vector from each sentence. **Parameters**: *vector_size*: the size of embedding vector. Increasing this parameters might improve accuracy, but will take longer to train (int, default=30) *epochs*: how many epochs should be applied during training. Inc... | display(hide_toggle())
X_train, X_test, y_train, y_test, classes = None, None, None, None, None
def dataset(obj):
global sentences_df, sentences_filepath, dataset_name, X_train, X_test, y_train, y_test, classes
clear_output()
display(hide_toggle())
display(HTML('<img src="../loading.gif" alt="Drawing" ... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Train classification modelTrain a deep neural network to classify each sentence to its correct label for 500 epochs (automatically stop when training no longer improves results)For the purpose of this demo, the network architecture and hyper-parameters are constant. Feel free the modify to code and improve the model | display(hide_toggle())
history, report, df_cm = None, None, None
def train(obj):
global dataset_name, X_train, X_test, y_train, y_test, classes, history, report, df_cm
train_button.description = 'Train Again'
clear_output()
display(hide_toggle())
display(train_button)
history, report, df_cm =... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
Evaluate the modelPlot the results of the model:- **Loss** - how did the model progress during training (lower values mean better performance)- **Accuracy** - how did the model perform on the validation set (higher values are better)- **Confusion Matrix** - mapping each of the model's predictions (x-axis) to its true ... | display(hide_toggle())
def evaluate(btn):
global history, report, df_cm
clear_output()
evaluate_button.description = 'Refresh'
display(hide_toggle())
display(evaluate_button)
plot_model_results(history, report, df_cm, classes)
evaluate_button = widgets.Button(description='Evaluate Mod... | _____no_output_____ | MIT | examples/complaints example.ipynb | imperva/mal2vec |
pyGSM (Python + GSM) pyGSM uses the powerful tools of python to allow for rapid prototyping and improved readability.* Reduction in number of lines ~12,000 vs ~30,000 and individual file size * Highly object oriented * Easy to read/use/prototype. No compiling!* No loss in performance since it uses high-performing nume... | import sys
sys.path.insert(0,'/home/caldaz/module/pyGSM')
from molecule import Molecule
from pes import PES
from avg_pes import Avg_PES
import numpy as np
from nifty import pvec1d,pmat2d
import matplotlib
import matplotlib.pyplot as plt
from pytc import *
import manage_xyz
from rhf_lot import *
from psiw import *
from ... | _____no_output_____ | MIT | examples/ipynb_demos/pytc/.ipynb_checkpoints/Basic_API-checkpoint.ipynb | espottesmith/pyGSM |
1. Building the pyTC objects | printcool("Build resources")
resources = ls.ResourceList.build()
printcool('{}'.format(resources))
printcool("build the Lightspeed (pyTC) objecs")
filepath='data/ethylene.xyz'
molecule = ls.Molecule.from_xyz_file(filepath)
geom = geometry.Geometry.build(
resources=resources,
molecule=molecule,
basisname='6... | #========================================================#
#| [92m build the Lightspeed (pyTC) objecs [0m |#
#========================================================#
#========================================================#
#| [92m Geometry: [0m |#
#| [92... | MIT | examples/ipynb_demos/pytc/.ipynb_checkpoints/Basic_API-checkpoint.ipynb | espottesmith/pyGSM |
Section 2: Building the pyGSM Objects | printcool("Build the pyGSM Level of Theory object (LOT)")
lot=PyTC.from_options(states=[(1,0),(1,1)],psiw=psiw,do_coupling=True,fnm=filepath)
printcool("Build the pyGSM Potential Energy Surface Object (PES)")
pes1 = PES.from_options(lot=lot,ad_idx=0,multiplicity=1)
pes2 = PES.from_options(lot=lot,ad_idx=1,multiplicity=... | #================================================================#
#| [92m Build the pyGSM Molecule object [0m |#
#| [92m with Translation and Rotation Internal Coordinates (TRIC) [0m |#
#================================================================#
reading cartesian coordinates fro... | MIT | examples/ipynb_demos/pytc/.ipynb_checkpoints/Basic_API-checkpoint.ipynb | espottesmith/pyGSM |
Section 3: API of Molecule Class | print(M)
print("printing gradient")
pvec1d(M.gradient,5,'f')
M.energy
print("primitive internal coordinates")
print(M.primitive_internal_coordinates)
printcool("primitive number of internal coordinates")
print(M.num_primitives)
printcool("getting the value of a primitive 0")
print(M.primitive_internal_coordinates[0].va... | #========================================================#
#| [92m copy molecule with new geom [0m |#
#========================================================#
initializing LOT from file
setting primitives from options!
getting cartesian coordinates from geom
getting coord_object from opti... | MIT | examples/ipynb_demos/pytc/.ipynb_checkpoints/Basic_API-checkpoint.ipynb | espottesmith/pyGSM |
Day 2 Assignment - 1 | Q.No.1 # List and its default functions
# (i) Add list element as value of list
# append():
list = ["Jansi","Jessie","Sheela","Thabita"]
list.append("jabamalar")
print(list)
# (ii) Insert():
# Insert at index value 1990
list.insert(1969,1990)
print(list)
# (iii) extend():
List1 = [12, 23, 34, 45]
List2 = [34, 45, 56... | Javascript
| MIT | Assignment - 1 ( Day 2 ).ipynb | jsharmi18421245/LetsUpgrade-pyhton |
Open Street Map Buildings InformationThis notebook demonstrates downloading data from Open Street Map to fill gaps in the [Global Electricity Transmission And Distribution Lines](https://datacatalog.worldbank.org/dataset/derived-map-global-electricity-transmission-and-distribution-lines) (GETD) dataset.To obtain GIS d... | from google.colab import drive
drive.mount('/content/drive') | Mounted at /content/drive
| MIT | Packages/Get_Data_From_OSM/Get_open_street_map_lines.ipynb | ryan0124/ACEP_Capstone_Project |
Get packagesInstall packages needed for analysis and import into workspace. | !pip install esy-osmfilter # gives tags and filters to open street map data
!pip install geopandas #to make working with geospatial data in python easier
%load_ext autoreload
%autoreload 2
import configparser, contextlib
import os, sys
import geopandas as gpd
import pandas as pd
from esy.osmfilter import osm_colors as ... | The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
| MIT | Packages/Get_Data_From_OSM/Get_open_street_map_lines.ipynb | ryan0124/ACEP_Capstone_Project |
To Downlaod the main pbf file (No need to run) | ## NO NEED TO RUN
!wget http://download.geofabrik.de/north-america/us/alaska-latest.osm.pbf -P '/content/drive/MyDrive/ACEP_Data_Team/Railbelt_line/Script_data/' | --2022-03-09 04:44:44-- http://download.geofabrik.de/north-america/us/alaska-latest.osm.pbf
Resolving download.geofabrik.de (download.geofabrik.de)... 95.216.28.113, 116.202.112.212
Connecting to download.geofabrik.de (download.geofabrik.de)|95.216.28.113|:80... connected.
HTTP request sent, awaiting response... 200 O... | MIT | Packages/Get_Data_From_OSM/Get_open_street_map_lines.ipynb | ryan0124/ACEP_Capstone_Project |
Function to download different types of buildings | # Getting residential buildings
def get_res_buildings(area_name):
# Set input/output locations
PBF_inputfile = os.path.join(os.getcwd(), '/content/drive/MyDrive/ACEP_Data_Team/Railbelt_line/Script_data/'+area_name+'-latest.osm.pbf')
JSON_outputfile = os.path.join(os.getcwd(),'/content/drive/MyDrive/ACEP_Data_T... | _____no_output_____ | MIT | Packages/Get_Data_From_OSM/Get_open_street_map_lines.ipynb | ryan0124/ACEP_Capstone_Project |
TensorFlow Neural Network Lab In this lab, you'll use all the tools you learned from *Introduction to TensorFlow* to label images of English letters! The data you are using, notMNIST, consists of images of a letter from A to J in different fonts.The above images are a few examples of the data you'll be training on. Aft... | import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
print('All m... | All modules imported.
| MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J). | ## 이미 로컬로 파일을 다운로드 받았으므로 이제 이것은 돌리지 않아도 됨.
def download(url, file):
"""
Download file from <url>
:param url: URL to file
:param file: Local file path
"""
if not os.path.isfile(file):
print('Downloading ' + file + '...')
urlretrieve(url, file)
print('Download Finished')
... | 100%|██████████████████████████████████████████████████████████| 210001/210001 [04:33<00:00, 767.96files/s]
100%|████████████████████████████████████████████████████████████| 10001/10001 [00:10<00:00, 937.99files/s]
| MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
Problem 1The first problem involves normalizing the features for your training and test data.Implement Min-Max scaling in the `normalize_grayscale()` function to a range of `a=0.1` and `b=0.9`. After scaling, the values of the pixels in the input data should range from 0.1 to 0.9.Since the raw notMNIST image data is i... | # Problem 1 - Implement Min-Max scaling for grayscale image data
def normalize_grayscale(image_data):
"""
Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
:param image_data: The image data to be normalized
:return: Normalized image data
"""
# TODO: Implement Min-Max scaling... | Saving data to pickle file...
Data cached in pickle file.
| MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
CheckpointAll your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed. | %matplotlib inline
# Load the modules
import pickle
import math
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import matplotlib.pyplot as plt
# Reload the data
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
pickle_data = pickle.load(f)
train_features = pickle_data['train_da... | Data and modules loaded.
| MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
Problem 2Now it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer.For the input here the images have been flattened into a vector of $28 \times 28 = 784$ features. Then, we're trying to predict the image digit so there are 10 output units, one ... | # All the pixels in the image (28 * 28 = 784)
features_count = 784
# All the labels
labels_count = 10
# TODO: Set the features and labels tensors
features = tf.placeholder(tf.float32)
labels = tf.placeholder(tf.float32)
# TODO: Set the weights and biases tensors
weights = tf.Variable(tf.truncated_normal((features_cou... | Accuracy function created.
| MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
Problem 3Below are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy.Parameter configurations:Configuration 1* **Epochs:** 1* **Learning Rate:** * 0.8 * 0.5 * 0.1 * 0... | # Change if you have memory restrictions
batch_size = 128
# TODO: Find the best parameters for each configuration
epochs = 10
learning_rate = 0.08
### DON'T MODIFY ANYTHING BELOW ###
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# The accuracy measured against t... | Epoch 1/10: 100%|████████████████████████████████████████████████| 1114/1114 [01:15<00:00, 14.83batches/s]
Epoch 2/10: 100%|████████████████████████████████████████████████| 1114/1114 [01:00<00:00, 18.32batches/s]
Epoch 3/10: 100%|████████████████████████████████████████████████| 1114/1114 [01:04<00:00, 17.37batches... | MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
Best Hyper-parameters1. **epochs**: 1, **Learning Rate**: 0.1 -> **Validation accuracy**: 0.7342. **epochs**: 5, **Learning Rate**: 0.2 -> **Validation accuracy**: 0.7603. **epochs**: 5, **Learning Rate**: 0.1 -> **Validation accuracy**: 0.766 TestYou're going to test your model against your hold out dataset/testing ... | ### DON'T MODIFY ANYTHING BELOW ###
# The accuracy measured against the test set
test_accuracy = 0.0
with tf.Session() as session:
session.run(init)
batch_count = int(math.ceil(len(train_features)/batch_size))
for epoch_i in range(epochs):
# Progress bar
batches_pbar = tqdm(r... | Epoch 1/10: 100%|███████████████████████████████████████████████| 1114/1114 [00:07<00:00, 149.98batches/s]
Epoch 2/10: 100%|███████████████████████████████████████████████| 1114/1114 [00:07<00:00, 158.93batches/s]
Epoch 3/10: 100%|███████████████████████████████████████████████| 1114/1114 [00:07<00:00, 157.26batches... | MIT | intro-to-tensorflow/intro_to_tensorflow.ipynb | postBG/deep-learning |
**Question 1:** Write a function `square` that squares its argument. | def square(x):
return x**2
grader.check("q1") | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**Question 2:** Write a function `negate` that negates its argument. | def negate(x):
return not x
grader.check("q2") | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**Question 3:** Assign `x` to the negation of `[]`. Use `negate`. | x = negate([])
x
grader.check("q3") | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**Question 4:** Assign `x` to the square of 6.25. Use `square`. | x = square(6.25)
x
grader.check("q4") | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**Question 5:** Plot $f(x) = \cos (x e^x)$ on $(0,10)$. | x = np.linspace(0, 10, 100)
y = np.cos(x * np.exp(x))
plt.plot(x, y) | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**Question 6:** Write a non-recursive infinite generator for the Fibonacci sequence `fiberator`. | def fiberator():
yield 0
yield 1
a, b = 0, 1
while True:
a, b = b, a + b
yield a
grader.check("q6") | _____no_output_____ | BSD-3-Clause | test/test-grade/notebooks/fails6H.ipynb | chrispyles/otter-grader |
**FAQ:**- weighting do sampler `dowhy.do_samplers.weighting_sampler.WeightingSampler` 是什么?应该是一个使用倾向得分估计(Logistic Regression) 的判别模型。 Do-sampler 简介--- by Adam Kelleher, Heyang Gong 编译The "do-sampler" is a new feature in DoWhy. 尽管大多数以潜在结果为导向的估算器都专注于估计 the specific contrast $E[Y_0 - Y_1]$, Pearlian inference 专注于更基本的因果量,如反... | import os, sys
sys.path.append(os.path.abspath("../../../"))
import numpy as np
import pandas as pd
import dowhy.api
N = 5000
z = np.random.uniform(size=N)
d = np.random.binomial(1., p=1./(1. + np.exp(-5. * z)))
y = 2. * z + d + 0.1 * np.random.normal(size=N)
df = pd.DataFrame({'Z': z, 'D': d, 'Y': y})
(df[df.D == 1].... | _____no_output_____ | MIT | docs/source/example_notebooks/do_sampler_demo.ipynb | Causal-Inference-ZeroToAll/dowhy |
结果比真实的因果效应高 60%. 那么,让我们为这些数据建立因果模型。 | from dowhy import CausalModel
causes = ['D']
outcomes = ['Y']
common_causes = ['Z']
model = CausalModel(df,
causes,
outcomes,
common_causes=common_causes,
proceed_when_unidentifiable=True) | WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs.
INFO:dowhy.causal_graph:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named "Unobserved Confounders" to reflect this.
INFO:dowhy.causal_model:M... | MIT | docs/source/example_notebooks/do_sampler_demo.ipynb | Causal-Inference-ZeroToAll/dowhy |
Now that we have a model, we can try to identify the causal effect. | identification = model.identify_effect() | INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['U', 'Z']
WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.
INFO:dowhy.causal_identifier:Continuing by ignoring these u... | MIT | docs/source/example_notebooks/do_sampler_demo.ipynb | Causal-Inference-ZeroToAll/dowhy |
Identification works! We didn't actually need to do this yet, since it will happen internally with the do sampler, but it can't hurt to check that identification works before proceeding. Now, let's build the sampler. | from dowhy.do_samplers.weighting_sampler import WeightingSampler
sampler = WeightingSampler(df,
causal_model=model,
keep_original_treatment=True,
variable_types={'D': 'b', 'Z': 'c', 'Y': 'c'}) | INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['U', 'Z']
WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.
INFO:dowhy.causal_identifier:Continuing by ignoring these u... | MIT | docs/source/example_notebooks/do_sampler_demo.ipynb | Causal-Inference-ZeroToAll/dowhy |
Now, we can just sample from the interventional distribution! Since we set the `keep_original_treatment` flag to `False`, any treatment we pass here will be ignored. Here, we'll just pass `None` to acknowledge that we know we don't want to pass anything.If you'd prefer to specify an intervention, you can just put the i... | interventional_df = sampler.do_sample(None)
(interventional_df[interventional_df.D == 1].mean() - interventional_df[interventional_df.D == 0].mean())['Y'] | _____no_output_____ | MIT | docs/source/example_notebooks/do_sampler_demo.ipynb | Causal-Inference-ZeroToAll/dowhy |
Introduction to PyTorch***********************Introduction to Torch's tensor library======================================All of deep learning is computations on tensors, which aregeneralizations of a matrix that can be indexed in more than 2dimensions. We will see exactly what this means in-depth later. First,lets loo... | # Author: Robert Guthrie
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Creating Tensors~~~~~~~~~~~~~~~~Tensors can be created from Python lists with the torch.Tensor()function. | # torch.tensor(data) creates a torch.Tensor object with the given data.
V_data = [1., 2., 3.]
V = torch.tensor(V_data)
print(V)
# Creates a matrix
M_data = [[1., 2., 3.], [4., 5., 6]]
M = torch.tensor(M_data)
print(M)
# Create a 3D tensor of size 2x2x2.
T_data = [[[1., 2.], [3., 4.]],
[[5., 6.], [7., 8.]]]
... | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
What is a 3D tensor anyway? Think about it like this. If you have avector, indexing into the vector gives you a scalar. If you have amatrix, indexing into the matrix gives you a vector. If you have a 3Dtensor, then indexing into the tensor gives you a matrix!A note on terminology:when I say "tensor" in this tutorial, i... | # Index into V and get a scalar (0 dimensional tensor)
print(V[0])
# Get a Python number from it
print(V[0].item())
# Index into M and get a vector
print(M[0])
# Index into T and get a matrix
print(T[0]) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
You can also create tensors of other datatypes. The default, as you cansee, is Float. To create a tensor of integer types, trytorch.LongTensor(). Check the documentation for more data types, butFloat and Long will be the most common. You can create a tensor with random data and the supplied dimensionalitywith torch.ran... | x = torch.randn((3, 4, 5))
print(x) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Operations with Tensors~~~~~~~~~~~~~~~~~~~~~~~You can operate on tensors in the ways you would expect. | x = torch.tensor([1., 2., 3.])
y = torch.tensor([4., 5., 6.])
z = x + y
print(z) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
See `the documentation `__ for acomplete list of the massive number of operations available to you. Theyexpand beyond just mathematical operations.One helpful operation that we will make use of later is concatenation. | # By default, it concatenates along the first axis (concatenates rows)
x_1 = torch.randn(2, 5)
y_1 = torch.randn(3, 5)
z_1 = torch.cat([x_1, y_1])
print(z_1)
# Concatenate columns:
x_2 = torch.randn(2, 3)
y_2 = torch.randn(2, 5)
# second arg specifies which axis to concat along
z_2 = torch.cat([x_2, y_2], 1)
print(z_2... | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Reshaping Tensors~~~~~~~~~~~~~~~~~Use the .view() method to reshape a tensor. This method receives heavyuse, because many neural network components expect their inputs to havea certain shape. Often you will need to reshape before passing your datato the component. | x = torch.randn(2, 3, 4)
print(x)
print(x.view(2, 12)) # Reshape to 2 rows, 12 columns
# Same as above. If one of the dimensions is -1, its size can be inferred
print(x.view(2, -1)) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Computation Graphs and Automatic Differentiation================================================The concept of a computation graph is essential to efficient deeplearning programming, because it allows you to not have to write theback propagation gradients yourself. A computation graph is simply aspecification of how yo... | # Tensor factory methods have a ``requires_grad`` flag
x = torch.tensor([1., 2., 3], requires_grad=True)
# With requires_grad=True, you can still do all the operations you previously
# could
y = torch.tensor([4., 5., 6], requires_grad=True)
z = x + y
print(z)
# BUT z knows something extra.
print(z.grad_fn) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
So Tensors know what created them. z knows that it wasn't read in froma file, it wasn't the result of a multiplication or exponential orwhatever. And if you keep following z.grad_fn, you will find yourself atx and y.But how does that help us compute a gradient? | # Lets sum up all the entries in z
s = z.sum()
print(s)
print(s.grad_fn) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
So now, what is the derivative of this sum with respect to the firstcomponent of x? In math, we want\begin{align}\frac{\partial s}{\partial x_0}\end{align}Well, s knows that it was created as a sum of the tensor z. z knowsthat it was the sum x + y. So\begin{align}s = \overbrace{x_0 + y_0}^\text{$z_0$} + \overbrace{x_1 ... | # calling .backward() on any variable will run backprop, starting from it.
s.backward()
print(x.grad) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Understanding what is going on in the block below is crucial for being asuccessful programmer in deep learning. | x = torch.randn(2, 2)
y = torch.randn(2, 2)
# By default, user created Tensors have ``requires_grad=False``
print(x.requires_grad, y.requires_grad)
z = x + y
# So you can't backprop through z
print(z.grad_fn)
# ``.requires_grad_( ... )`` changes an existing Tensor's ``requires_grad``
# flag in-place. The input flag de... | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
You can also stop autograd from tracking history on Tensorswith ``.requires_grad``=True by wrapping the code block in``with torch.no_grad():`` | print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad) | _____no_output_____ | BSD-3-Clause | docs/_downloads/c4bf1a4ba1714ace73ad54fe5c6d9d00/pytorch_tutorial.ipynb | leejh1230/PyTorch-tutorials-kr |
Feature Engenering | SUFFIX_CAT = '__cat'
for feat in df.columns:
if isinstance( df[feat][0], list): continue
factorized_values = df[feat].factorize()[0]
if SUFFIX_CAT in feat:
df[feat] = factorized_values
else:
df[feat + SUFFIX_CAT] = df[feat].factorize()[0]
cat_feats = [x for x in df.columns if SUFFIX_CAT in x]
cat_fea... | _____no_output_____ | MIT | day4.ipynb | mszzukowski/dw_matrix_car |
DecisionTree | run_model(DecisionTreeRegressor(max_depth=5), cat_feats) | _____no_output_____ | MIT | day4.ipynb | mszzukowski/dw_matrix_car |
Random Forest | model = RandomForestRegressor(max_depth=5, n_estimators=50, random_state=0)
run_model(model=model, feats=cat_feats) | _____no_output_____ | MIT | day4.ipynb | mszzukowski/dw_matrix_car |
XGBoost | xgb_params = {
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
run_model(xgb.XGBRegressor(**xgb_params), cat_feats)
m = xgb.XGBRegressor(**xgb_params)
m.fit(X,y)
imp = PermutationImportance(m, random_state=0).fit(X,y)
eli5.show_weights(imp, feature_names=cat_feats)
feats = [
'par... | _____no_output_____ | MIT | day4.ipynb | mszzukowski/dw_matrix_car |
Riddler Battle Royale> [538's *The Riddler* Asks](http://fivethirtyeight.com/features/the-battle-for-riddler-nation-round-2/): *In a distant, war-torn land, there are 10 castles. There are two warlords: you and your archenemy, with whom you’re competing to collect the most victory points. Each castle has its own strat... | # Load some useful modules
%matplotlib inline
import matplotlib.pyplot as plt
import csv
import random
from collections import Counter
from statistics import mean | _____no_output_____ | MIT | ipynb/Riddler Battle Royale.ipynb | mikiec84/pytudes |
Let's play with this and see if we can find a good solution. Some implementation choices:* A `Plan` will be a tuple of 10 soldier counts (one for each castle).* `castles` will hold the indexes of the castles. Note that index 0 is castle 1 (worth 1 point) and index 9 is castle 10 (worth 10 points).* `half` is half the t... | Plan = tuple
castles = range(10)
half = 55/2
plans = {Plan(map(int, row[:10]))
for row in csv.reader(open('battle_royale.csv'))}
def play(A, B):
"Play Plan A against Plan B and return a reward (0, 1/2, or 1)."
A_points = sum(reward(A[c], B[c], c + 1) for c in castles)
return... | _____no_output_____ | MIT | ipynb/Riddler Battle Royale.ipynb | mikiec84/pytudes |
Some tests: | assert reward(6, 5, 9) == 9 # 6 soldiers defeat 5, winning all 9 of the castle's points
assert reward(6, 6, 8) == 4 # A tie on an 8-point castle is worth 4 points
assert reward(6, 7, 7) == 0 # No points for a loss
assert reward(30, 25) == 1 # 30 victory points beats 25
assert len(plans) == 1202
assert play((26, ... | _____no_output_____ | MIT | ipynb/Riddler Battle Royale.ipynb | mikiec84/pytudes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.