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 |
|---|---|---|---|---|---|
** Predict the Big Mountain resort `Adult Weekend` price and print it out.** This is our expected price to present to management. Based on our model given the characteristics of the resort in comparison to other ski resorts and their unique characteristics. | price=model4.predict(features)
price | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
** Print the Big Mountain resort actual `Adult Weekend` price.** | ac=df[df['Name'].str.contains('Big Mountain')]
print ("The actual Big Mountain Resort adult weekend price is $%s " % ' '.join(map(str, ac.AdultWeekend))) | The actual Big Mountain Resort adult weekend price is $81.0
| MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
** As part of reviewing the results it is an important step to generate figures to visualize the data story. We can use the clusters we added to our data frame to create scatter plots for visualizing the Adult Weekend values compared to other characteristics. Run the example below to get you started and build two or th... | plt.scatter(df['summit_elev'], df['vertical_drop'], c=df['clusters'], s=50, cmap='viridis', label ='clusters',edgecolors='white')
plt.scatter(ac['summit_elev'], ac['vertical_drop'], c='white', s=200,edgecolors='black')
sns.despine()
plt.xlabel('Summit Elevation (feet)')
plt.ylabel('Vertical Elevation Drop (feet)')
#plt... | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
Finalize Code Making sure our code is well organized and easy to follow is an important step. This is the time where you need to review the notebooks and Python scripts you've created and clean them up so they are easy to follow and succinct in nature. Addtionally, we will also save our final model as a callable obje... | import pickle
s = pickle.dumps(model4)
from joblib import dump, load
dump(model4, 'models/regression_model_adultweekend.joblib') | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
Finalize Documentation For model documentation, we want to save the model performance metrics as well as the features included in the final model. You could also save the model perfomance metrics and coefficients fo the other models you tried in case you want to refer to them later. ** Create a dataframe containing th... | performance_metrics=pd.DataFrame(abs(model4.coef_), X.columns, columns=['Coefficient'])
performance_metrics['Mean Absolute Error']= mean_absolute_error(y_test, ypred)
performance_metrics['Root Mean Squared Error']=np.sqrt(mean_squared_error(y_test, ypred))
performance_metrics['r2-testscore']=model4.score(X_test,y_test)... | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
2d. Distributed training and monitoring In this notebook, we refactor to use the Experimenter class instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training capa... | import google.datalab.ml as ml
import tensorflow as tf
from tensorflow.contrib import layers
print tf.__version__
# print ml.sdk_location
import datalab.bigquery as bq
import tensorflow as tf
import numpy as np
import shutil | _____no_output_____ | Apache-2.0 | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- |
Input Read data created in Lab1a, but this time make it more general, so that we are reading in batches. Instead of using Pandas, we will use add a filename queue to the TensorFlow graph. | CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']
LABEL_COLUMN = 'fare_amount'
DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]
def read_dataset(filename, num_epochs=None, batch_size=512, mode=tf.contrib.learn.ModeKeys.TRAIN):
def _input_fn():
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- |
Create features out of input data For now, pass these through. (same as previous lab) | INPUT_COLUMNS = [
layers.real_valued_column('pickuplon'),
layers.real_valued_column('pickuplat'),
layers.real_valued_column('dropofflat'),
layers.real_valued_column('dropofflon'),
layers.real_valued_column('passengers'),
]
feature_cols = INPUT_COLUMNS | _____no_output_____ | Apache-2.0 | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- |
Experiment framework | import tensorflow.contrib.learn as tflearn
from tensorflow.contrib.learn.python.learn import learn_runner
import tensorflow.contrib.metrics as metrics
def experiment_fn(output_dir):
return tflearn.Experiment(
tflearn.LinearRegressor(feature_columns=feature_cols, model_dir=output_dir),
train_input_f... | _____no_output_____ | Apache-2.0 | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- |
Monitoring with TensorBoard | from google.datalab.ml import TensorBoard
TensorBoard().start('./taxi_trained')
TensorBoard().list()
# to stop TensorBoard
TensorBoard().stop(23002)
print 'stopped TensorBoard'
TensorBoard().list() | _____no_output_____ | Apache-2.0 | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- |
Actor and Critic Method パッケージの準備 | %load_ext autoreload
%autoreload 2
%matplotlib inline
from google.colab import drive
drive.mount('/content/drive')
import sys
import os
HOME_PATH = '/content/drive/MyDrive/Colab Notebooks/baby-steps-of-rl-ja/exercise/day_3'
sys.path.append(HOME_PATH)
import numpy as np
import gym
from el_agent import ELAgent
from froz... | _____no_output_____ | Apache-2.0 | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja |
Actor の定義 | class Actor(ELAgent):
def __init__(self, env):
super().__init__(epsilon=-1)
n_row = env.observation_space.n
n_col = env.action_space.n
self.actions = list(range(env.action_space.n))
self.Q = np.random.uniform(0, 1, n_row * n_col).reshape((n_row, n_col))
def softmax(self, x):
return np.exp... | _____no_output_____ | Apache-2.0 | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja |
Critic の定義 | class Critic():
def __init__(self, env):
n_state = env.observation_space.n
self.V = np.zeros(n_state) | _____no_output_____ | Apache-2.0 | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja |
Actor & Critic 学習プロセスの定義 | class ActorCritic():
def __init__(self, actor_class, critic_class):
self.actor_class = actor_class
self.critic_class = critic_class
def train(self, env, episode_count=1000, gamma=0.9, learning_rate=0.1, render=False, report_interval=50):
actor = self.actor_class(env)
critic = self.critic_class(en... | _____no_output_____ | Apache-2.0 | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja |
Agent を学習させる | def train():
trainer = ActorCritic(Actor, Critic)
env = gym.make("FrozenLakeEasy-v0")
actor, critic = trainer.train(env, episode_count=3000)
show_q_value(actor.Q)
actor.show_reward_log()
agent = train() | At Episode 50 average reward is 0.02 (+/-0.14).
At Episode 100 average reward is 0.0 (+/-0.0).
At Episode 150 average reward is 0.0 (+/-0.0).
At Episode 200 average reward is 0.06 (+/-0.237).
At Episode 250 average reward is 0.04 (+/-0.196).
At Episode 300 average reward is 0.02 (+/-0.14).
At Episode 350 average reward... | Apache-2.0 | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja |
[Oregon Curriculum Network](http://www.4dsolutions.net/ocn) [Discovering Math with Python](Introduction.ipynb) Quadrays and GrapheneBy AlexanderAlUS - Own work, CC BY-SA 3.0, Link"Graphene" refers to an hexagonal grid of cells, the vertexes being carbon atoms. However any hexagonal mesh, such as for game boards, might... | from itertools import permutations
g = permutations((2,1,1,0))
unique = {p for p in g} # set comprehension
print(unique) | {(0, 1, 1, 2), (1, 0, 1, 2), (2, 0, 1, 1), (0, 2, 1, 1), (0, 1, 2, 1), (1, 2, 1, 0), (1, 1, 2, 0), (2, 1, 1, 0), (1, 0, 2, 1), (1, 2, 0, 1), (2, 1, 0, 1), (1, 1, 0, 2)}
| MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
I have [elsewhere](Generating%20the%20FCC.ipynb) used this fact to algorithmically generate consecutive shells of 12, 42, 92, 162... spheres (balls) respectively; a growing cuboctahedron of $10 S^{2} + 2$ balls per shell S = 1,2,3... (1 when S=0).H... | from qrays import Qvector, IVM
A, B, C, D = Qvector((1,0,0,0)), Qvector((0,1,0,0)), Qvector((0,0,1,0)), Qvector((0,0,0,1))
E,F,G,H = B+C+D, A+C+D, A+B+D, A+B+C
I,J,K,L,M,N = A+B, A+C, A+D, B+C, B+D, C+D
O,P,Q,R,S,T = I+J, I+K, I+L, I+M, N+J, N+K; U,V,W,X,Y,Z = N+L, N+M, J+L, L+M, M+K, K+J
# two "beacons" of six spokes... | _____no_output_____ | MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
Lets verify that, going around the hexagon, each pair of consecutive hexrays is 60 degree apart. And ditto for hoprays, the vectors we'll use to jump over the fence to neighboring hexagon centers. | (hoprays[0].angle(hoprays[1]),
hoprays[1].angle(hoprays[2]),
hoprays[2].angle(hoprays[3]),
hoprays[3].angle(hoprays[4]),
hoprays[4].angle(hoprays[5]),
hoprays[5].angle(hoprays[0])) | _____no_output_____ | MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
Looks like we're in business!As with the growing cuboctahedron and the CCP packing, it makes sense to think in terms of consecutive rings.The [hexagonal coordination sequence](https://oeis.org/A008458) is generated by: | def A008458(n):
# OEIS number
if n == 0:
return 1
return 6 * n
[A008458(x) for x in range(10)] | _____no_output_____ | MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
I will use this as a check as the algorithm generates multiple rings. | centers = {IVM(0,0,0,0)} # center face
edges = set() # no duplicates permitted
carbons = set()
ring0 = [Qvector((0,0,0,0))]
def next_ring(ring):
"""
Use only the most recently added hexagonal ring
of face centers to compute the next ring, moving
outward: 1, 6, 12, 18, 24...
"""
... | Ring: 0 Number: 1
Ring: 1 Number: 6
Ring: 2 Number: 12
Ring: 3 Number: 18
Ring: 4 Number: 24
Ring: 5 Number: 30
Ring: 6 Number: 36
Ring: 7 Number: 42
Ring: 8 Number: 48
Ring: 9 Number: 54
Ring: 10 Number: 60
Ring: 11 Number: 66
| MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
Note these are the expected numbers for consecutive rings.Now that we have our database, it's time to generate some graphical output. As with the FCC, I'll use [POV-Ray's scene description language](http://www.4dsolutions.net/ocn/numeracy0.html) and then render in [POV-Ray](http://www.povray.org). We just want to loo... | sph = """sphere { %s 0.1 texture { pigment { color rgb <1,0,0> } } }"""
cyl = """cylinder { %s %s 0.05 texture { pigment { color rgb <1.0, 0.65, 0.0> } } }"""
def make_graphene(fname="../c6xty/graphene.pov", append=True):
"""
Scan through carbons, edges, converting to XYZ and embedding
in POV-Ray Scene Des... | _____no_output_____ | MIT | GrapheneWithQrays.ipynb | 4dsolutions/Python5 |
(image-segmentation:relabel-sequential)= Sequential object (re-)labelingAs mentioned above, depending on the use-case it might be important to label objects in an image subsequently. It could for example be that a post-processing algorithm for label images crashes in case we pass a label image with missing labels. Henc... | import numpy as np
from skimage.io import imread
from skimage.segmentation import relabel_sequential
import pyclesperanto_prototype as cle | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Our starting point is a label image with labels 1-8, where some labels are not present: | label_image = imread("../../data/label_map_with_index_gaps.tif")
cle.imshow(label_image, labels=True) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
When measuring the maximum intensity in the image, we can see that this label image containing 4 labels is obviously not sequentially labeled. | np.max(label_image) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
We can use the `unique` function to figure out which labels are present: | np.unique(label_image) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Sequential labelingWe can now relabel this image and remove these gaps using [scikit-image's `relabel_sequential()` function](https://scikit-image.org/docs/dev/api/skimage.segmentation.htmlskimage.segmentation.relabel_sequential). We're entering the `_` as additional return variables as we're not interested in them. T... | relabeled, _, _ = relabel_sequential(label_image)
cle.imshow(relabeled, labels=True) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Afterwards, the unique labels should be sequential: | np.unique(relabeled) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Also pyclesperanto has a function for relabeling label images sequentially. The result is supposed identical to the result in scikit-image. It just doesn't return the additional values. | relabeled1 = cle.relabel_sequential(label_image)
cle.imshow(relabeled1, labels=True) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Reverting sequential labelingIn some cases we apply an operation to a label image that returns a new label image with less labels that are sequentially labeled but the label-identity is lost. This happens for example when excluding labels from the label image that are too small. | large_labels = cle.exclude_small_labels(relabeled, maximum_size=260)
cle.imshow(large_labels, labels=True, max_display_intensity=4)
np.unique(large_labels) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
To restore the original label identities, we need to multiply a binary image representing the remaining labels with the original label image. | binary_remaining_labels = large_labels > 0
cle.imshow(binary_remaining_labels)
large_labels_with_original_identity = binary_remaining_labels * relabeled
cle.imshow(large_labels_with_original_identity, labels=True, max_display_intensity=4)
np.unique(large_labels_with_original_identity) | _____no_output_____ | CC-BY-4.0 | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks |
Multiple single-step forecast models models studied in Zoumpekas et al (2020) | import random
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
from tensorflow.keras.layers import Dense, Input, Conv1D, LSTM, GRU, Bidirectional, Dropout, Flatten
from tensorflow.keras import Model, Sequential
from tensorflow.keras.initializers import Rand... | Epoch 1/50
400/400 [==============================] - 52s 129ms/step - loss: 5134155.0000 - val_loss: 36836.4336
Epoch 2/50
400/400 [==============================] - 51s 128ms/step - loss: 784477.2500 - val_loss: 21840.3535
Epoch 3/50
400/400 [==============================] - 51s 129ms/step - loss: 224073.4531 - val_... | MIT | multimodel-1obs-1step.ipynb | righthandabacus/market_notebooks |
Scaling Criteo: Triton Inference with HugeCTR OverviewThe last step is to deploy the ETL workflow and saved model to production. In the production setting, we want to transform the input data as during training (ETL). We need to apply the same mean/std for continuous features and use the same categorical mapping to co... | import os
import numpy as np | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Now we move our saved `.model` files inside 1 folder. We use only the last snapshot after `9600` iterations. | os.system("mv *9600.model ./criteo_hugectr/1/") | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Now we can save our models to be deployed at the inference stage. To do so we will use export_hugectr_ensemble method below. With this method, we can generate the config.pbtxt files automatically for each model. In doing so, we should also create a hugectr_params dictionary, and define the parameters like where the ama... | import nvtabular as nvt
BASE_DIR = os.environ.get("BASE_DIR", "/raid/data/criteo")
input_path = os.path.join(BASE_DIR, "test_dask/output")
workflow = nvt.Workflow.load(os.path.join(input_path, "workflow")) | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Let's clear the directory | os.system("rm -rf /model/*")
from nvtabular.inference.triton import export_hugectr_ensemble
hugectr_params = dict()
hugectr_params["config"] = "/model/criteo/1/criteo.json"
hugectr_params["slots"] = 26
hugectr_params["max_nnz"] = 1
hugectr_params["embedding_vector_size"] = 128
hugectr_params["n_outputs"] = 1
export_hu... | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We can take a look at the generated files. | !tree /model | [01;34m/model[00m
├── [01;34mcriteo[00m
│ ├── [01;34m1[00m
│ │ ├── 0_opt_sparse_9600.model
│ │ ├── [01;34m0_sparse_9600.model[00m
│ │ │ ├── emb_vector
│ │ │ ├── key
│ │ │ └── slot_id
│ │ ├── _dense_9600.model
│ │ ├── _opt_dense_9600.model
│ │ └── criteo.json
│ └── confi... | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We need to write a configuration file with the stored model weights and model configuration. | %%writefile '/model/ps.json'
{
"supportlonglong": true,
"models": [
{
"model": "criteo",
"sparse_files": ["/model/criteo/1/0_sparse_9600.model"],
"dense_file": "/model/criteo/1/_dense_9600.model",
"network_file": "/model/criteo/1/criteo.json",
... | Overwriting /model/ps.json
| Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Loading Ensemble Model with Triton Inference ServerWe have only saved the models for Triton Inference Server. We started Triton Inference Server in explicit mode, meaning that we need to send a request that Triton will load the ensemble model. We connect to the Triton Inference Server. | import tritonhttpclient
try:
triton_client = tritonhttpclient.InferenceServerClient(url="localhost:8000", verbose=True)
print("client created.")
except Exception as e:
print("channel creation failed: " + str(e)) | client created.
| Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We deactivate warnings. | import warnings
warnings.filterwarnings("ignore") | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We check if the server is alive. | triton_client.is_server_live() | GET /v2/health/live, headers None
<HTTPSocketPoolResponse status=200 headers={'content-length': '0', 'content-type': 'text/plain'}>
| Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We check the available models in the repositories:- criteo_ens: Ensemble - criteo_nvt: NVTabular - criteo: HugeCTR model | triton_client.get_model_repository_index() | POST /v2/repository/index, headers None
<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '93'}>
bytearray(b'[{"name":".ipynb_checkpoints"},{"name":"criteo"},{"name":"criteo_ens"},{"name":"criteo_nvt"}]')
| Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We load the models individually. | %%time
triton_client.load_model(model_name="criteo_nvt")
%%time
triton_client.load_model(model_name="criteo")
%%time
triton_client.load_model(model_name="criteo_ens") | POST /v2/repository/models/criteo_ens/load, headers None
<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>
Loaded model 'criteo_ens'
CPU times: user 4.7 ms, sys: 0 ns, total: 4.7 ms
Wall time: 20.2 s
| Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Example Request to Triton Inference ServerNow, the models are loaded and we can create a sample request. We read an example **raw batch** for inference. | # Get dataframe library - cudf or pandas
from merlin.core.dispatch import get_lib
df_lib = get_lib()
# read in the workflow (to get input/output schema to call triton with)
batch_path = os.path.join(BASE_DIR, "converted/criteo")
batch = df_lib.read_parquet(os.path.join(batch_path, "*.parquet"), num_rows=3)
batch = ba... | I1 I2 I3 I4 I5 I6 I7 I8 I9 I10 ... C17 \
0 5 110 <NA> 16 <NA> 1 0 14 7 1 ... -771205462
1 32 3 5 <NA> 1 0 0 61 5 0 ... -771205462
2 <NA> 233 1 146 1 0 0 99 7 0 ... -771205462
C18 C19 C... | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We prepare the batch for inference by using correct column names and data types. We use the same datatypes as defined in our dataframe. | batch.dtypes
import tritonclient.http as httpclient
from tritonclient.utils import np_to_triton_dtype
inputs = []
col_names = list(batch.columns)
col_dtypes = [np.int32] * len(col_names)
for i, col in enumerate(batch.columns):
d = batch[col].fillna(0).values_host.astype(col_dtypes[i])
d = d.reshape(len(d), 1... | _____no_output_____ | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
We send the request to the triton server and collect the last output. | # placeholder variables for the output
outputs = [httpclient.InferRequestedOutput("OUTPUT0")]
# build a client to connect to our server.
# This InferenceServerClient object is what we'll be using to talk to Triton.
# make the request with tritonclient.http.InferInput object
response = triton_client.infer("criteo_ens",... | POST /v2/models/criteo_ens/infer, headers {'Inference-Header-Content-Length': 3383}
b'{"id":"1","inputs":[{"name":"I1","shape":[3,1],"datatype":"INT32","parameters":{"binary_data_size":12}},{"name":"I2","shape":[3,1],"datatype":"INT32","parameters":{"binary_data_size":12}},{"name":"I3","shape":[3,1],"datatype":"INT32",... | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
Let's unload the model. We need to unload each model. | triton_client.unload_model(model_name="criteo_ens")
triton_client.unload_model(model_name="criteo_nvt")
triton_client.unload_model(model_name="criteo") | POST /v2/repository/models/criteo_ens/unload, headers None
{"parameters":{"unload_dependents":false}}
<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>
Loaded model 'criteo_ens'
POST /v2/repository/models/criteo_nvt/unload, headers None
{"parameters":{"unload_depend... | Apache-2.0 | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular |
NNCLR* Nearest- Neighbor Contrastive Learning of visual Representations (NNCLR), samples the nearest neighbors from the dataset in the latent space, and treats them as positives. This provides more semantic variations than pre-defined transformations.* NNCLR Formulated by Google Research and DeepMind
data_base_dir
!pwd
fname = os.path.join(data_base_dir, 'processed', 'index.h5')
fname = Path(fname)
#fname = '../data/processed/index.h5'
# Load dataset from HDF storage
with pd.HDFStore(fname) as storage:
djia = storage.get('nyse/cleaned/rand_symbols')
y_2c ... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Imputing missing values | X.shape
check_for_missing_vals(X) | No missing values found in dataframe
| MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Prices values | prices.shape
check_for_missing_vals(prices)
y_3c.shape
check_for_missing_vals(y_3c)
y2.shape
check_for_missing_vals(y2) | No missing values found in dataframe
| MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
No missing values, and sizes of ```y.shape[0]``` and```X.shape[0]``` match. Scaling the features | from sklearn.preprocessing import MinMaxScaler, StandardScaler
#scale = MinMaxScaler()
scale = StandardScaler()
scaled = scale.fit_transform(X)
scaled.shape
#X_scaled = pd.DataFrame(data=scaled, columns=X.columns)
X_scaled = X | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Train-Test Split | # Use 70/30 train/test splits
test_p = .3
# Scaled, three-class
test_size = int((1 - test_p) * X_scaled.shape[0])
X_train, X_test, y_train, y_test = X_scaled[:test_size], X_scaled[test_size:], y_3c[:test_size], y_3c[test_size:]
prices_train, prices_test = djia[:test_size], djia[test_size:]
# Unscaled, two-class
test_si... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Model | symbol_list
symbol = 'T'
n1 = 15
n2 = 15
n_estimators = 10
# set up cross validation splits
tscv = TimeSeriesSplit(n_splits=5)
btscv = BlockingTimeSeriesSplit(n_splits=5)
#ppcv = PurgedKFold(n_splits=5)
# Creates a list of features for a given lookback window (n1)
features = [f'{x}_{n1}' for x in ti_list]
# Creates a l... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Single lookback/lookahead combination | clf_svc1 = OneVsRestClassifier(
BaggingClassifier(
SVC(
kernel='rbf',
class_weight='balanced'
),
max_samples=.4,
n_estimators=n_estimators,
n_jobs=-1)
)
clf_svc1.fit... | Accuracy Score: 0.5400340715502555
precision recall f1-score support
0 0.91 0.52 0.66 505
1 0.19 0.68 0.29 82
accuracy 0.54 587
macro avg 0.55 0.60 0.48 587
weighted avg... | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
All combinations Averaging across all 50 randomly selected stocks | avg_results, scores_dict, preds_dict, params_dict, returns_dict = avg_model(
symbol_list,
forecast_horizon,
input_window_size,
X_train,
X_test,
y_train,
y_test,
prices_test,
model=clf_svc1,
silent ... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Hyperparamter Optimization: GridSearch | gsearch_xgb.best_score_ | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Hyperparamter Optimization: Bayesian Optimization XGBoost | n1=15
n2=15
symbol='T'
y_train[symbol][f'signal_{n2}'].value_counts()
symbol_list
# Optimizing for accuracy_score
model = XGBClassifier
bsearch_xgba, clf_bsearch_xgba, params_bsearch_xgba = BayesianSearch(
search_space(model),
model,
X_train[symbol][features],
y_train[symbol][f'signal_{n2}'],
X_te... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
XGBoost with all features | # Accuracy as scoring metric
n1=15
n2=15
symbol='T'
model = XGBClassifier
bsearch_xgb1, clf_bsearch_xgb1, params_bsearch_xgb1 = BayesianSearch(
search_space(model),
model,
X_train[symbol][all_features],
y_train[symbol][f'signal_{n2}'],
X_test[symbol][all_features],
y_test[symbol][f'signal_{n2}... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Running on all 50 stocks on best model | #best_params = {'bootstrap': False, 'criterion': 'gini', 'max_depth': 218, 'max_features': 1, 'min_samples_leaf': 19, 'n_estimators': 423}
#model_2a = (n_jobs=-1, **params_rf4)
avg_results, scores_dict, preds_dict, params_dict, returns_dict = avg_model(
symbol_list,
forecast_horizon, ... | _____no_output_____ | MIT | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf |
Settings | %env TF_KERAS = 1
import os
sep_local = os.path.sep
import sys
sys.path.append('..'+sep_local+'..')
print(sep_local)
os.chdir('..'+sep_local+'..'+sep_local+'..'+sep_local+'..'+sep_local+'..')
print(os.getcwd())
import tensorflow as tf
print(tf.__version__) | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Dataset loading | dataset_name='pokemon'
images_dir = 'C:\\Users\\Khalid\\Documents\projects\\pokemon\DS06\\'
validation_percentage = 20
valid_format = 'png'
from training.generators.file_image_generator import create_image_lists, get_generators
imgs_list = create_image_lists(
image_dir=images_dir,
validation_pct=validation_per... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Model's Layers definition | units=20
c=50
enc_lays = [
tf.keras.layers.Conv2D(filters=units, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(filters=units*9, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
# No activation
tf.keras.layers.Dense(latents_dim)
]
dec_lays = [... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Model definition | model_name = dataset_name+'AE_Convolutional_reconst_1ell_01psnr'
experiments_dir='experiments'+sep_local+model_name
from training.autoencoding_basic.autoencoders.autoencoder import autoencoder as AE
inputs_shape=image_size
variables_params = \
[
{
'name': 'inference',
'inputs_shape':inputs_shape,
... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Callbacks |
from training.callbacks.sample_generation import SampleGeneration
from training.callbacks.save_model import ModelSaver
es = tf.keras.callbacks.EarlyStopping(
monitor='loss',
min_delta=1e-12,
patience=12,
verbose=1,
restore_best_weights=False
)
ms = ModelSaver(filepath=_restore)
csv_dir = os.pa... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Model Training | ae.fit(
x=train_ds,
input_kw=None,
steps_per_epoch=int(1e4),
epochs=int(1e6),
verbose=2,
callbacks=[ es, ms, csv_log, sg],
workers=-1,
use_multiprocessing=True,
validation_data=test_ds,
validation_steps=int(1e4)
) | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Model Evaluation inception_score | from evaluation.generativity_metrics.inception_metrics import inception_score
is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200)
print(f'inception_score mean: {is_mean}, sigma: {is_sigma}') | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Frechet_inception_distance | from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance
fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32)
print(f'frechet inception distance: {fis_score}') | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
perceptual_path_length_score | from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score
ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32)
print(f'perceptual path length score: {ppl_mean_score}') | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
precision score | from evaluation.generativity_metrics.precision_recall import precision_score
_precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'precision score: {_precision_score}') | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
recall score | from evaluation.generativity_metrics.precision_recall import recall_score
_recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'recall score: {_recall_score}') | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Image Generation image reconstruction Training dataset | %load_ext autoreload
%autoreload 2
from training.generators.image_generation_testing import reconstruct_from_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
reconstruct_from_a_... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
with Randomness | from training.generators.image_generation_testing import generate_images_like_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
generate_images_like_a_batch(ae, training_generator, ... | _____no_output_____ | MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Complete Randomness | from training.generators.image_generation_testing import generate_images_randomly
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'random_synthetic_dir')
create_if_not_exist(save_dir)
generate_images_randomly(ae, save_dir)
from training.generators.image_generati... | 100%|██████████| 15/15 [00:00<00:00, 19.90it/s]
| MIT | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models |
Compute ICA on MEG data and remove artifacts============================================ICA is fit to MEG raw data.The sources matching the ECG and EOG are automatically found and displayed.Subsequently, artifact detection and rejection quality are assessed. | # Authors: Denis Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.preprocessing import ICA
from mne.preprocessing import create_ecg_epochs, create_eog_epochs
from mne.datasets import sample | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io |
Setup paths and prepare raw data. | data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, None, fir_design='firwin') # already lowpassed @ 40
raw.annotations = mne.Annotations([1], [10], 'BAD')
raw.plot(block=True)
# For the sake of example ... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io |
1) Fit ICA model using the FastICA algorithm.Other available choices are ``picard``, ``infomax`` or ``extended-infomax``.NoteThe default method in MNE is FastICA, which along with Infomax is one of the most widely used ICA algorithm. Picard is a new algorithm that is expected to converge faster than F... | ica = ICA(n_components=0.95, method='fastica', random_state=0, max_iter=100)
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False,
stim=False, exclude='bads')
ica.fit(raw, picks=picks, decim=3, reject=dict(mag=4e-12, grad=4000e-13),
verbose='warning') # low iterations -> doe... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io |
2) identify bad components by analyzing latent sources. | title = 'Sources related to %s artifacts (red)'
# generate ECG epochs use detection via phase statistics
ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
ica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg')
sh... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io |
3) Assess component selection and unmixing quality. | # estimate average artifact
ecg_evoked = ecg_epochs.average()
ica.plot_sources(ecg_evoked, exclude=ecg_inds) # plot ECG sources + selection
ica.plot_overlay(ecg_evoked, exclude=ecg_inds) # plot ECG cleaning
eog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average()
ica.plot_sources(eog_evoked, exc... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io |
Torch Hub Inference TutorialIn this tutorial you'll learn:- how to load a pretrained model using Torch Hub - run inference to classify the action in a demo video Install and Import modules If `torch`, `torchvision` and `pytorchvideo` are not installed, run the following cell: | try:
import torch
except ModuleNotFoundError:
!pip install torch torchvision
import os
import sys
import torch
if torch.__version__=='1.6.0+cu101' and sys.platform.startswith('linux'):
!pip install pytorchvideo
else:
need_pytorchvideo=False
try:
# Running notebook locally
... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
Setup Download the id to label mapping for the Kinetics 400 dataset on which the Torch Hub models were trained. This will be used to get the category label names from the predicted class ids. | !wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json
with open("kinetics_classnames.json", "r") as f:
kinetics_classnames = json.load(f)
# Create an id to label name mapping
kinetics_id_to_classname = {}
for k, v in kinetics_classnames.items():
kinetics_id_to_classname[... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
Load Model using Torch Hub APIPyTorchVideo provides several pretrained models through Torch Hub. Available models are described in [model zoo documentation](https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.mdkinetics-400). Here we are selecting the `slowfast_r50` model which was trained... | # Device on which to run the model
# Set to cuda to load on GPU
device = "cpu"
# Pick a pretrained model
model_name = "slowfast_r50"
model = torch.hub.load("facebookresearch/pytorchvideo:main", model=model_name, pretrained=True)
# Set to eval mode and move to desired device
model = model.to(device)
model = model.eva... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
Define the transformations for the input required by the modelBefore passing the video into the model we need to apply some input transforms and sample a clip of the correct duration.NOTE: The input transforms are specific to the model. If you choose a different model than the example in this tutorial, please refer to... | ####################
# SlowFast transform
####################
side_size = 256
mean = [0.45, 0.45, 0.45]
std = [0.225, 0.225, 0.225]
crop_size = 256
num_frames = 32
sampling_rate = 2
frames_per_second = 30
alpha = 4
class PackPathway(torch.nn.Module):
"""
Transform for converting video frames as a list of ten... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
Load an example videoWe can test the classification of an example video from the kinetics validation set such as this [archery video](https://www.youtube.com/watch?v=3and4vWkW4s). | # Download the example video file
!wget https://dl.fbaipublicfiles.com/pytorchvideo/projects/archery.mp4
# Load the example video
video_path = "archery.mp4"
# Select the duration of the clip to load by specifying the start and end duration
# The start_sec should correspond to where the action occurs in the video
st... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
Get model predictions | # Pass the input clip through the model
preds = model(inputs)
# Get the predicted classes
post_act = torch.nn.Softmax(dim=1)
preds = post_act(preds)
pred_classes = preds.topk(k=5).indices
# Map the predicted classes to the label names
pred_class_names = [kinetics_id_to_classname[int(i)] for i in pred_classes[0]]
pri... | _____no_output_____ | Apache-2.0 | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo |
ANN Metrics | def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
true_positives = K.sum(K.round(... | _____no_output_____ | MIT | Boda/ensemble/NN.ipynb | UVA-DSI-2019-Capstones/UVACyber |
ANN Model | tests[tests.label == 1]
df = pd.read_csv('/scratch/by8jj/stratified samples/ensemble model/file.csv')
len(df)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df.drop('label', axis = 1), df.label, test_size=0.2)
X_train['label'] = y_train
X_train
df_mal = X_trai... | precision: 81.6491971891807
recall: 89.35790853042899
false positive rate: 1.0073213698881054
accuracy 98.5325078797032
F1-score 0.8532980501964162
| MIT | Boda/ensemble/NN.ipynb | UVA-DSI-2019-Capstones/UVACyber |
Submitting various things for end of grant. | import os
import sys
import requests
import pandas
import paramiko
import json
from IPython import display
from curation_common import *
from htsworkflow.submission.encoded import DCCValidator
PANDAS_ODF = os.path.expanduser('~/src/pandasodf')
if PANDAS_ODF not in sys.path:
sys.path.append(PANDAS_ODF)
from pand... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Submit Documents Example Document submission | #atac_uuid = '0fc44318-b802-474e-8199-f3b6d708eb6f'
#atac = Document(os.path.expanduser('~/proj/encode3-curation/Wold_Lab_ATAC_Seq_protocol_December_2016.pdf'),
# 'general protocol',
# 'ATAC-Seq experiment protocol for Wold lab',
# )
#body = atac.create_if_needed(server, ata... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Submit Annotations | #sheet = gcat.get_file(spreadsheet_name, fmt='pandas_excel')
#annotations = sheet.parse('Annotations', header=0)
#created = server.post_sheet('/annotations/', annotations, verbose=True, dry_run=True)
#print(len(created))
#if created:
# annotations.to_excel('/tmp/annotations.xlsx', index=False) | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Register Biosamples | book = ODFReader(spreadsheet_name)
biosample = book.parse('Biosample', header=0)
created = server.post_sheet('/biosamples/', biosample,
verbose=True,
dry_run=True,
validator=validator)
print(len(created))
if created:
biosample.to... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Register Libraries | print(spreadsheet_name)
book = ODFReader(spreadsheet_name)
libraries = book.parse('Library', header=0)
created = server.post_sheet('/libraries/',
libraries,
verbose=True,
dry_run=True,
validator=validator... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Register Experiments | book = ODFReader(spreadsheet_name)
experiments = book.parse('Experiment', header=0)
created = server.post_sheet('/experiments/',
experiments,
verbose=True,
dry_run=False,
validator=validator)
print(len(cr... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Register Replicates | book = ODFReader(spreadsheet_name)
replicates = book.parse('Replicate', header=0)
created = server.post_sheet('/replicates/',
replicates,
verbose=True,
dry_run=True,
validator=validator)
print(len(created... | _____no_output_____ | BSD-3-Clause | 10x-3-to-13-submission.ipynb | detrout/encode4-curation |
Image extraction from folders and creating image set | def CreateTrainSet(positive_path, negative_path, IMAGE_WIDTH, IMAGE_HEIGHT, Positive_Images=1200):
# getting all file names from positive path
positives = os.listdir(positive_path)
positive_files = [os.path.join(positive_path, file_name) for file_name in positives if file_name.endswith('.jpg')]
positive_fil... | Path exists: True
train_images: (1480, 128, 64)
train_labels: (1480,)
[[196 197 201 ... 124 119 117]
[195 197 200 ... 125 118 115]
[195 196 200 ... 126 116 111]
...
[181 181 181 ... 182 181 181]
[178 178 177 ... 184 184 184]
[176 176 175 ... 186 186 186]]
0
[[198 198 197 ... 123 113 106]
[196 196 196 ... 121 1... | MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
Getting Hog features and creating training feature set | # returns HoG features, and orderd features
def HoG_features(images):
cell_size = (8,8)
block_size = (4,4)
nbins = 4
# all images have same shape
img_size = images[0].shape
# creating HoG object
hog = cv2.HOGDescriptor(_winSize=(img_size[1] // cell_size[1] * cell_size[1],
... | trained_features_reshaped: (1480, 4160)
trained_features_reshaped[0]: [0.03915166 0.0065741 0.00676362 ... 0.0232183 0.02239115 0.00087363]
| MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
Non-linear SVM Classifier | def NonLinear_SVM(train_features, train_labels, gamma, C, random_state=None):
# creating non-linear svc object, RBF kernel is default
clf = svm.SVC(C=C, gamma=gamma, random_state=random_state)
# fit and predict
clf.fit(train_features, train_labels)
return clf
def predict(clf, test_features... | _____no_output_____ | MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
1 Fold Validation | k_fold = 5
pos_count = Positive_Images
neg_count = 280
pos_train_split = int(pos_count*4/k_fold)
neg_train_split = int(pos_count+neg_count*4/k_fold)
print(f"train_size: {pos_train_split+neg_train_split-pos_count}")
print(f"test_size: {pos_count-pos_train_split+neg_count-neg_train_split+pos_count}")
# splitti... | _____no_output_____ | MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
5 Fold Cross Validation | def k_fold_SVC(train_features, train_labels, train_index, val_index, k_folds):
total_accuracy = 0
for i in range(k_folds):
x_train, x_val = train_features[train_index], train_features[val_index]
y_train, y_val = train_labels[train_index], train_labels[val_index]
clf = NonLinear_SVM(... | _____no_output_____ | MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
Using Optimal Paramaeters for SVM Classifier | # Optimal SVM Classifer
gamma = "scale"
C = 10
Optimal_Clf = NonLinear_SVM(train_features_split, train_labels_split, gamma, C)
accuracy = predict(clf, val_features_split, val_labels_split)
print(f"Gamma: {gamma}, C: {C}, Accuracy: {round(accuracy, 2)}%") | Gamma: scale, C: 10, Accuracy: 96.62%
| MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.