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 |
|---|---|---|---|---|---|
Train cdcgan model | %%bash
gsutil -m rm -rf ${OUTPUT_DIR}
export PYTHONPATH=$PYTHONPATH:$PWD/cdcgan_module
python3 -m trainer.task \
--train_file_pattern=${TRAIN_FILE_PATTERN} \
--eval_file_pattern=${EVAL_FILE_PATTERN} \
--output_dir=${OUTPUT_DIR} \
--job-dir=./tmp \
\
--train_batch_size=${TRAIN_BATCH_SIZE} \
-... | _____no_output_____ | Apache-2.0 | machine_learning/gan/cdcgan/tf_cdcgan/tf_cdcgan_run_module_local.ipynb | ryangillard/artificial_intelligence |
Prediction | import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
!gsutil ls gs://machine-learning-1234-bucket/gan/cdcgan/trained_model2/export/exporter
predict_fn = tf.contrib.predictor.from_saved_model(
"gs://machine-learning-1234-bucket/gan/cdcgan/trained_model2/export/exporter/1592859903"
)
predictions... | ['generated_images']
| Apache-2.0 | machine_learning/gan/cdcgan/tf_cdcgan/tf_cdcgan_run_module_local.ipynb | ryangillard/artificial_intelligence |
Convert image back to the original scale. | generated_images = np.clip(
a=((predictions["generated_images"] + 1.0) * (255. / 2)).astype(np.int32),
a_min=0,
a_max=255
)
print(generated_images.shape)
def plot_images(images):
"""Plots images.
Args:
images: np.array, array of images of
[num_images, height, width, depth].
... | _____no_output_____ | Apache-2.0 | machine_learning/gan/cdcgan/tf_cdcgan/tf_cdcgan_run_module_local.ipynb | ryangillard/artificial_intelligence |
Check surface fluxes of CO$_2$ | # check the data folder to swith to another mixing conditions
#ds = xr.open_dataset('data/results_so4_adv/5_po75-25_di10e-9/water.nc')
ds = xr.open_dataset('data/results_so4_adv/9_po75-25_di30e-9/water.nc')
#ds = xr.open_dataset('data/no_denitrification/water.nc')
dicflux_df = ds['B_C_DIC _flux'].to_dataframe()
oxyfl... | _____no_output_____ | CC-BY-3.0 | s_6_air-sea_and_advective_fluxes_WS.ipynb | limash/ws_notebook |
Advective TA exchange These are data on how alkalinity in the Wadden Sea changes due to mixing with the North Sea. Positive means alkalinity comes from the North Sea, negative - goes to the North Sea. | nh4ta_df = ds['TA_due_to_NH4'].to_dataframe()
no3ta_df = ds['TA_due_to_NO3'].to_dataframe()
po4ta_df = ds['TA_due_to_PO4'].to_dataframe()
so4ta_df = ds['TA_due_to_SO4'].to_dataframe()
nh4ta_year = nh4ta_df.loc['2011-01-01':'2011-12-31']
no3ta_year = no3ta_df.loc['2011-01-01':'2011-12-31']
po4ta_year = po4ta_df.loc['201... | _____no_output_____ | CC-BY-3.0 | s_6_air-sea_and_advective_fluxes_WS.ipynb | limash/ws_notebook |
here and further, units: mmol m$^{-2}$ | nh4ta
sum(nh4ta)
no3ta
sum(no3ta)
po4ta
sum(po4ta)
so4ta
sum(so4ta)
total
sum(total) | _____no_output_____ | CC-BY-3.0 | s_6_air-sea_and_advective_fluxes_WS.ipynb | limash/ws_notebook |
Scatter Plot with MinimapThis example shows how to create a miniature version of a plot such that creating a selection in the miniature version adjusts the axis limits in another, more detailed view. | import altair as alt
from vega_datasets import data
source = data.seattle_weather()
zoom = alt.selection_interval(encodings=["x", "y"])
minimap = (
alt.Chart(source)
.mark_point()
.add_selection(zoom)
.encode(
x="date:T",
y="temp_max:Q",
color=alt.condition(zoom, "weather", al... | _____no_output_____ | MIT | doc/gallery/scatter_with_minimap.ipynb | mattijn/altdoc |
Using Ray for Highly Parallelizable TasksWhile Ray can be used for very complex parallelization tasks,often we just want to do something simple in parallel.For example, we may have 100,000 time series to process with exactly the same algorithm,and each one takes a minute of processing.Clearly running it on a single pr... | import ray
import random
import time
import math
from fractions import Fraction
# Let's start Ray
ray.init(address='auto') | INFO:anyscale.snapshot_util:Synced git objects for /home/ray/workspace-project-waleed_test1 to /efs/workspaces/shared_objects in 0.07651424407958984s.
INFO:anyscale.snapshot_util:Created snapshot for /home/ray/workspace-project-waleed_test1 at /tmp/snapshot_2022-05-16T16:38:57.388956_otbjcv41.zip of size 1667695 in 0.0... | Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
We use the ``@ray.remote`` decorator to create a Ray task.A task is like a function, except the result is returned asynchronously.It also may not run on the local machine, it may run elsewhere in the cluster.This way you can run multiple tasks in parallel,beyond the limit of the number of processors you can have in a s... | @ray.remote
def pi4_sample(sample_count):
"""pi4_sample runs sample_count experiments, and returns the
fraction of time it was inside the circle.
"""
in_count = 0
for i in range(sample_count):
x = random.random()
y = random.random()
if x*x + y*y <= 1:
in_count +... | _____no_output_____ | Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
To get the result of a future, we use ray.get() which blocks until the result is complete. | SAMPLE_COUNT = 1000 * 1000
start = time.time()
future = pi4_sample.remote(sample_count = SAMPLE_COUNT)
pi4 = ray.get(future)
end = time.time()
dur = end - start
print(f'Running {SAMPLE_COUNT} tests took {dur} seconds') | Running 1000000 tests took 1.4935967922210693 seconds
| Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
Now let's see how good our approximation is. | pi = pi4 * 4
float(pi)
abs(pi-math.pi)/pi | _____no_output_____ | Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
Meh. A little off -- that's barely 4 decimal places.Why don't we do it a 100,000 times as much? Let's do 100 billion! | FULL_SAMPLE_COUNT = 100 * 1000 * 1000 * 1000 # 100 billion samples!
BATCHES = int(FULL_SAMPLE_COUNT / SAMPLE_COUNT)
print(f'Doing {BATCHES} batches')
results = []
for _ in range(BATCHES):
results.append(pi4_sample.remote())
output = ray.get(results) | Doing 100000 batches
| Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
Notice that in the above, we generated a list with 100,000 futures.Now all we do is have to do is wait for the result.Depending on your ray cluster's size, this might take a few minutes.But to give you some idea, if we were to do it on a single machine,when I ran this it took 0.4 seconds.On a single core, that means we... | pi = sum(output)*4/len(output)
float(pi)
abs(pi-math.pi)/pi | _____no_output_____ | Apache-2.0 | doc/source/ray-core/examples/highly_parallel.ipynb | minds-ai/ray |
Lambda School Data Science*Unit 2, Sprint 1, Module 3*--- Ridge Regression AssignmentWe're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.But not just for condos in Tribeca...- [ ] Use a subset of the data where `BUILDING_CLAS... | import numpy as np
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
# Ignore t... | RIDGE train MAE 151103.0875222934
RIDGE test MAE 155194.34287168915
| MIT | module3-ridge-regression/LS_DS_213_assignment.ipynb | Collin-Campbell/DS-Unit-2-Linear-Models |
Zircon model training notebook; (extensively) modified from Detectron2 training tutorialThis Colab Notebook will allow users to train new models to detect and segment detrital zircon from RL images using Detectron2 and the training dataset provided in the colab_zirc_dims repo. It is set up to train a Mask RCNN model (... | !pip install pyyaml==5.1
import torch
TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
CUDA_VERSION = torch.__version__.split("+")[-1]
print("torch: ", TORCH_VERSION, "; cuda: ", CUDA_VERSION)
# Install detectron2 that matches the above pytorch version
# See https://detectron2.readthedocs.io/tutorials/instal... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Define Augmentations The cell below defines augmentations used while training to ensure that models never see the same exact image twice during training. This mitigates overfitting and allows models to achieve substantially higher accuracy in their segmentations/measurements. | custom_transform_list = [T.ResizeShortestEdge([800,800]), #resize shortest edge of image to 800 pixels
T.RandomCrop('relative', (0.95, 0.95)), #randomly crop an area (95% size of original) from image
T.RandomLighting(100), #minor lighting randomization
... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Mount Google Drive, set paths to dataset, model saving directories | from google.colab import drive
drive.mount('/content/drive')
#@markdown ### Add path to training dataset directory
dataset_dir = '/content/drive/MyDrive/training_dataset' #@param {type:"string"}
#@markdown ### Add path to model saving directory (automatically created if it does not yet exist)
model_save_dir = '/conten... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Define dataset mapper, training, loss eval functions | from detectron2.engine import DefaultTrainer
from detectron2.data import DatasetMapper
from detectron2.structures import BoxMode
# a function to convert Via image annotation .json dict format to Detectron2 \
# training input dict format
def get_zircon_dicts(img_dir):
json_file = os.path.join(img_dir, "via_region_d... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Import train, val catalogs | #registers training, val datasets (converts annotations using get_zircon_dicts)
for d in ["train", "val"]:
DatasetCatalog.register("zircon_" + d, lambda d=d: get_zircon_dicts(dataset_dir + "/" + d))
MetadataCatalog.get("zircon_" + d).set(thing_classes=["zircon"])
zircon_metadata = MetadataCatalog.get("zircon_tr... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Visualize train dataset | # visualize random sample from training dataset
dataset_dicts = get_zircon_dicts(os.path.join(dataset_dir, 'train'))
for d in random.sample(dataset_dicts, 4): #change int here to change sample size
img = cv2.imread(d["file_name"])
visualizer = Visualizer(img[:, :, ::-1], metadata=zircon_metadata, scale=0.5)
... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Define save to Drive function | # a function to save models (with iteration number in name), metrics to drive; \
# important in case training crashes or is left unattended and disconnects. \
def save_outputs_to_drive(model_name, iters):
root_output_dir = os.path.join(model_save_dir, model_name) #output_dir = save dir from user input
#creates ind... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Build, train model Set some parameters for training | #@markdown ### Add a base name for the model
model_save_name = 'your model name here' #@param {type:"string"}
#@markdown ### Final iteration before training stops
final_iteration = 8000 #@param {type:"slider", min:3000, max:15000, step:1000} | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Actually build and train model | #train from a pre-trained Mask RCNN model
cfg = get_cfg()
# train from base model: Default Mask RCNN
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml"))
# Load starting weights (COCO trained) from Detectron2 model zoo.
cfg.MODEL.WEIGHTS = "https://dl.fbaipublicfiles.... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Inference & evaluation with final trained model Initialize model from saved weights: | cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth") # final model; modify path to other non-final model to view their segmentations
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set a custom testing threshold
cfg.MODEL.RPN.NMS_THRESH = 0.1
predictor = DefaultPredictor(cfg) | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
View model segmentations for random sample of images from zircon validation dataset: | from detectron2.utils.visualizer import ColorMode
dataset_dicts = get_zircon_dicts(os.path.join(dataset_dir, 'val'))
for d in random.sample(dataset_dicts, 5):
im = cv2.imread(d["file_name"])
outputs = predictor(im) # format is documented at https://detectron2.readthedocs.io/tutorials/models.html#model-outp... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Validation eval with COCO API metric: | from detectron2.evaluation import COCOEvaluator, inference_on_dataset
from detectron2.data import build_detection_test_loader
evaluator = COCOEvaluator("zircon_val", ("bbox", "segm"), False, output_dir="./output/")
val_loader = build_detection_test_loader(cfg, "zircon_val")
print(inference_on_dataset(trainer.model, val... | _____no_output_____ | Apache-2.0 | training dataset/ResNet_colab_zirc_dims_train_model.ipynb | MCSitar/colab-zirc-dims |
Analysis | # Prepare data
demographic = pd.read_csv('../data/processed/demographic.csv')
severity = pd.read_csv('../data/processed/severity.csv', index_col=0)
features = demographic.columns
X = demographic.astype(np.float64)
y = (severity >= 4).sum(axis=1)
needs_to_label = {0:'no needs', 1:'low_needs', 2:'moderate needs', 3:'hig... | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Understanding the features | from yellowbrick.features import Rank2D
from yellowbrick.features.manifold import Manifold
from yellowbrick.features.pca import PCADecomposition
from yellowbrick.style import set_palette
set_palette('flatui') | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Feature covariance plot | visualizer = Rank2D(algorithm='covariance')
visualizer.fit(X, y)
visualizer.transform(X)
visualizer.poof() | /home/muhadriy/.conda/envs/ml/lib/python3.6/site-packages/yellowbrick/features/rankd.py:262: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
X = X.as_matrix()
| RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Principal Component Projection | visualizer = PCADecomposition(scale=True, color = y_c, proj_dim=3)
visualizer.fit_transform(X, y)
visualizer.poof() | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Manifold projections | visualizer = Manifold(manifold='tsne', target='discrete')
visualizer.fit_transform(X, y)
visualizer.poof()
visualizer = Manifold(manifold='modified', target='discrete')
visualizer.fit_transform(X, y)
visualizer.poof() | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
No apparent structure from the PCA and Manifold projections. Class Balance | categories, counts = np.unique(y, return_counts=True)
fig, ax = plt.subplots(figsize=(9, 7))
sb.set(style="whitegrid")
sb.barplot(labels, counts, ax=ax, tick_label=labels)
ax.set(xlabel='Need Categories',
ylabel='Number of HHs'); | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Heavy class imbalances. Use appropriate scoring metrics/measures. Learning and Validation | from sklearn.model_selection import StratifiedKFold
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import RidgeClassifier
from yellowbrick.model_selection import LearningCurve
cv = StratifiedKFold(10)
sizes = np.linspace(0.1, 1., 20)
visualizer = LearningCurve(RidgeClassifier(), cv=cv, train_sizes... | _____no_output_____ | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Classification | from sklearn.linear_model import RidgeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_select... | Balanced accuracy: 0.25
Classification report:
pre rec spe f1 geo iba sup
no needs 0.20 0.02 1.00 0.03 0.13 0.01 63
low needs 0.52 0.18 0.95 0.27 0.42 0.16 594
moderate ... | RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Voting Classifier Hard Voting | clf1 = KNeighborsClassifier(weights='distance')
clf2 = GaussianNB()
clf3 = ExtraTreesClassifier(class_weight='balanced_subsample')
clf4 = GradientBoostingClassifier()
vote = VotingClassifier(estimators=[('knn', clf1), ('gnb', clf2), ('ext', clf3), ('gb', clf4)], voting='hard')
params = {'knn__n_neighbors': [2,3,4], 'gb... | Fitting 5 folds for each of 81 candidates, totalling 405 fits
| RSA-MD | notebooks/.ipynb_checkpoints/Analysis-checkpoint.ipynb | mmData/Hack4Good |
Import packages | import warnings
warnings.filterwarnings("ignore")
import pandas as pd
# general packages
import numpy as np
import matplotlib.pyplot as plt
import os
import seaborn as sns
# sklearn models
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Logi... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
sklearn models | from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.metrics import confusion_matrix
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifie... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Load preprocessed data | with open(os.path.join('data','Xdict.pickle'),'rb') as handle1:
Xdict = pickle.load(handle1)
with open(os.path.join('data','ydict.pickle'),'rb') as handle2:
ydict = pickle.load(handle2)
subjects = list(set(Xdict.keys())) | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
FEATURE ENGINEERING Need to first make a master dataframe for the 5,6 numbers with corresponding result for all subjects compiled | s01 = ydict[1]
df1 = pd.DataFrame(s01, columns=['Result'])
df1['Subject'] = 1
df1['Time Series'] = [series[:-52] for series in Xdict[1].tolist()]
df1['Psd'] = [series[950:] for series in Xdict[1].tolist()]
df1
s02 = ydict[2]
df2 = pd.DataFrame(s02, columns=['Result'])
df2['Subject'] = 2
df2['Time Series'] = [series[:-... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Splitting the psd into 52 different columns so each value can be used as a feature: | resultframe[['psd'+str(i) for i in range(1,53)]] = pd.DataFrame(resultframe.Psd.values.tolist(), index= resultframe.index)
resultframe = resultframe.drop('Psd', axis=1)
resultframe.head() | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Assuming the merged table is formed correctly, we now have our outcomes ('Results') and their corresponding first 950 time points series data, and subject information. We no longer have information regarding which electrode collected the data (irrelevant since no biological correspondence), however, if needed, we can ... | countframe = resultframe.groupby("Subject").count().drop('Time Series', axis=1).drop(['psd'+str(i) for i in range(1,53)], axis=1)
countframe
plt.bar(countframe.index, countframe['Result'])
plt.xlabel('Subject')
plt.ylabel('Count')
plt.title('Number of Entries per subject')
plt.show(); | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Note: Number of Entries = Number of trials with first number as 5,6 * Number of electrodes for the subjectIn preprocessing notebook, we determined the number of electrodes per subject to be as followed: | subject = [1,2,3,4,5,6,7,8,9,10]
electrodes = [5,6,59,5,61,7,11,10,19,16]
elecframe = pd.DataFrame(data={'Subject': subject, 'Num Electrode' : electrodes})
elecframe | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
In preprocessing notebook, we also determined the number of trials with 5 and 6 (in cleaned table, excluding all types of bad trials): | subject = [1,2,3,4,5,6,7,8,9,10]
num5 = [23, 24, 24, 12, 21, 22, 21, 24, 24, 16]
num6 = [20, 23, 24, 18, 21, 24, 22, 24, 24, 18]
trialframe = pd.DataFrame(data={'Subject': subject, 'Num 5': num5, 'Num 6': num6})
trialframe['Num Total Trials'] = trialframe['Num 5'] + trialframe['Num 6']
trialframe = trialframe.drop(['N... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Merging the two tables together: | confframe = pd.concat([elecframe, trialframe.drop('Subject', axis=1)], axis=1)
confframe['Expected Entries'] = confframe['Num Electrode'] * confframe['Num Total Trials']
confframe
checkframe = pd.merge(confframe, countframe, how='inner', left_on='Subject', right_index=True)
checkframe | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
We now confirmed that our expected number of entries per subject matches the actual number of entries we obtained in the master dataframe created above. This indicates that the table above is likely created properly and it is safe to use it for further analysis.Next, we need to understand the characteristics of our dat... | outframe = resultframe.groupby('Result').count().drop('Time Series', axis=1).drop(['psd'+str(i) for i in range(1,53)], axis=1).rename(index=str, columns={'Subject':'Count'})
outframe | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
We can observe that the distribution is not even between the two possible outcomes so we need to be careful when assessing the performance of our model. We will next calculate the prediction power of chance: | total = sum(outframe['Count'])
outframe['Probability'] = outframe['Count']/total
outframe | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
We can observe that the probability of getting a correct prediction due to purely chance is 56.988% (~57%) so we need to design a prediction model that performs better than this. We will now move on to feature engineering to create new features. Making new features: We currently have 52 power spectral density (psd) fe... | resultframe.head()
resultframe['Max'] = [max(i) for i in resultframe['Time Series']]
resultframe['Min'] = [min(i) for i in resultframe['Time Series']]
resultframe['Std'] = [np.std(i) for i in resultframe['Time Series']]
resultframe['Mean'] = [np.mean(i) for i in resultframe['Time Series']]
resultframe['p2.5'] = [np.per... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Changing entries of "Result"Safebet = 0, Gamble = 1: | resultframe['Result'] = resultframe['Result'].map({'Safebet': 0, 'Gamble': 1})
resultframe.head() | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
We should center all our data to 0.0 since we care about relative wave form and not baseline amplitude. The difference in baseline amplitude can be ascribed to hardware differences (electrode readings) and should not be considered in our predictive model. Thus, we need to adapt our features above by centering the value... | resultframe['Max'] = resultframe['Max'] - resultframe['Mean']
resultframe['Min'] = resultframe['Min'] - resultframe['Mean']
resultframe['p2.5'] = resultframe['p2.5'] - resultframe['Mean']
resultframe['p97.5'] = resultframe['p97.5'] - resultframe['Mean']
resultframe['Mean'] = resultframe['Mean'] - resultframe['Mean']
re... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Since all the features currently in place are statistics that do not respect the temporal nature of our data (time-series data), we need to introduce features that also respect the morphology of the waves in the data. An example feature is number of peaks.Number of peaks = number of data points i where i > i-1 and i > ... | peaks = []
for series in resultframe['Time Series']:
no_peaks = 0
indices = range(2,949)
for index in indices:
if series[index] > series[index-1] and series[index] > series[index+1]:
no_peaks += 1
peaks.append(no_peaks)
len(peaks)
resultframe['Num Peaks'] = peaks
resultframe.... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Categorizing all our data | resultframe['Num Peaks Cat'] = pd.cut(resultframe['Num Peaks'], 4,labels=[1,2,3,4])
#resultframe = resultframe[['Subject', 'Time Series', 'Max', 'Min', 'Interval', 'Std', 'p2.5', 'p97.5', 'Percentile Interval', 'Num Peaks', 'Num Peaks Cat', 'Result']]
resultframe.head()
resultframe['p2.5 Cat'] = pd.qcut(resultframe['p... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Checking our X and y matrices (selecting only features we want to pass into the model) | resultframe.loc[:,["Subject", "Result"]][resultframe['Subject']==1].drop('Subject', axis=1).head()
#resultframe.iloc[:,[1,3]][resultframe['Subject']==1].drop("Subject", axis=1).head()
resultframe.drop(["Subject", "Time Series", "Result"], axis=1) | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Modeling Logistic Regression Initialize dataframe to track model performance per subject | performance_logistic = pd.DataFrame(index = Xdict.keys(), # subject
columns=['naive_train_accuracy',
'naive_test_accuracy',
'model_train_accuracy',
'... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Train model | coefficients = dict()
# initialize dataframes to log predicted choice and true choice for each trial
predictions_logistic_train_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
predictions_logistic_test_master = pd.DataFrame(columns=['predicted_choi... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
FEATURE SELECTIONsince not much improvement has been seen in iter5, I will attempt to selectivly include features from our current feature set that demonstrates strong predictive powers. I will first see any collinear features | train, test = train_test_split(resultframe, test_size=0.2, random_state=100)
train_df = train.iloc[:, 2:]
train_df.head()
train_df.corr()
colormap = plt.cm.viridis
plt.figure(figsize=(12,12))
plt.title('Pearson Correlation of Features', y=1.05, size=15)
sns.heatmap(train_df.corr().round(2)\
,linewidths=0.1... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
As seen in the chart above, the correlation between different features is generally pretty high. Thus, we need to be more selective in choosing features for this model as uncorrelated features are generally more powerful predictorsWill try these features: num peaks cat, percentile interval, std, p97.5 cat, p2.5 cat Ra... | performance_forest = pd.DataFrame(index = Xdict.keys(), # subject
columns=['naive_train_accuracy',
'naive_test_accuracy',
'model_train_accuracy',
'mo... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Initialize dataframes to log predicted choice and true choice for each trial | feature_importances = dict()
predictions_forest_train_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
predictions_forest_test_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
rand... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Overfits a lot logistic regression modified with StandardScaler(), i.e., z-scoring the data before fitting model initialize dataframe to track model performance per subject | performance_logistic = pd.DataFrame(index = Xdict.keys(), # subject
columns=['naive_train_accuracy',
'naive_test_accuracy',
'model_train_accuracy',
'... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
initialize dataframes to log predicted choice and true choice for each trial | predictions_logistic_train_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
predictions_logistic_test_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
LogisticRegressionModel = line... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
random forest with StandardScaler() initialize dataframe to track model performance per subject | performance_forest = pd.DataFrame(index = Xdict.keys(), # subject
columns=['naive_train_accuracy',
'naive_test_accuracy',
'model_train_accuracy',
'mo... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
initialize dataframes to log predicted choice and true choice for each trial | feature_importances = dict()
predictions_forest_train_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
predictions_forest_test_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
rand... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
logistic regression with StandardScaler() *and* selecting K best features (reducing the number of features, should reduce overfitting) initialize dataframe to track model performance per subject | performance_logistic = pd.DataFrame(index = Xdict.keys(), # subject
columns=['naive_train_accuracy',
'naive_test_accuracy',
'model_train_accuracy',
'... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
initialize dataframes to log predicted choice and true choice for each trial | predictions_logistic_train_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
predictions_logistic_test_master = pd.DataFrame(columns=['predicted_choice',
'true_choice'])
LogisticRegressionModel = line... | _____no_output_____ | MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
try different numbers of num_k | num_k = [1,2,3,4] # max number of features is 4
for k in num_k:
pipe = make_pipeline(SelectKBest(k=k), StandardScaler(), linear_model.LogisticRegressionCV())
LogisticRegressionModel = pipe
# two subclasses to start
for subject in subjects:
print(subject)
X = resultframe.iloc[:,[0,4,6,7... | 1
2
3
| MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
Trying other models | X = resultframe.iloc[:,[4,6,7,8]]
y = resultframe.iloc[:,-1]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100)
print ('Number of samples in training data:',len(x_train))
print ('Number of samples in test data:',len(x_test))
perceptron = Perceptron(max_iter=100)
perceptron.fit... | random_forest training acuracy= 0.7377796779250392
random_forest test accuracy= 0.5162393162393163
| MIT | Model History/Adi_iter6/Adi Iter 6.ipynb | dattasiddhartha/DataX-NeuralDecisionMaking |
> ------ Gaussian boson sampling tutorial To get a feel for how Strawberry Fields works, let's try coding a quantum program, Gaussian boson sampling. Background information: Gaussian states---A Gaussian state is one that can be described by a [Gaussian function](https://en.wikipedia.org/wiki/Gaussian_f... | import strawberryfields as sf
from strawberryfields.ops import *
from strawberryfields.utils import random_interferometer | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
Strawberry Fields makes this easy; there is an `Interferometer` quantum operation, and a utility function that allows us to generate the matrix representing a random interferometer. | U = random_interferometer(4) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
The lack of Fock states and non-linear operations means we can use the Gaussian backend to simulate Gaussian boson sampling. In this example program, we are using input states with squeezing parameter $\xi=1$, and the randomly chosen interferometer generated above. | eng, q = sf.Engine(4)
with eng:
# prepare the input squeezed states
S = Sgate(1)
All(S) | q
# interferometer
Interferometer(U) | q
state = eng.run('gaussian') | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
We can see the decomposed beamsplitters and rotation gates, by calling `eng.print_applied()`: | eng.print_applied() | Run 0:
Sgate(1, 0) | (q[0])
Sgate(1, 0) | (q[1])
Sgate(1, 0) | (q[2])
Sgate(1, 0) | (q[3])
Rgate(-1.77) | (q[0])
BSgate(0.3621, 0) | (q[0], q[1])
Rgate(0.4065) | (q[2])
BSgate(0.7524, 0) | (q[2], q[3])
Rgate(-0.5894) | (q[1])
BSgate(0.9441, 0) | (q[1], q[2])
Rgate(0.2868) | (q[0])
BSgate(0.8913, 0) | (q[0], q[1])
Rgate... | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
**Available decompositions**Check out our documentation to see the available CV decompositions available in Strawberry Fields. Analysis---Let's now verify the Gaussian boson sampling result, by comparing the output Fock state probabilities to the Hafnian, using the relationship$$\left|\left\langle{n_1,n_2,\dots,n_N}\m... | B = (np.dot(U, U.T) * np.tanh(1)) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
In Gaussian boson sampling, we determine the submatrix by taking the rows and columns corresponding to the measured Fock state. For example, to calculate the submatrix in the case of the output measurement $\left|{1,1,0,0}\right\rangle$, | B[:,[0,1]][[0,1]] | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
To calculate the Hafnian in Python, we can use the direct definition$$\text{Haf}(A) = \frac{1}{n!2^n} \sum_{\sigma \in S_{2n}} \prod_{j=1}^n A_{\sigma(2j - 1), \sigma(2j)}$$Notice that this function counts each term in the definition multiple times, and renormalizes to remove the multiple counts by dividing by a factor... | from itertools import permutations
from scipy.special import factorial
def Haf(M):
n=len(M)
m=int(n/2)
haf=0.0
for i in permutations(range(n)):
prod=1.0
for j in range(m):
prod*=M[i[2*j],i[2*j+1]]
haf+=prod
return haf/(factorial(m)*(2**m)) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
Comparing to the SF result In Strawberry Fields, both Fock and Gaussian states have the method `fock_prob()`, which returns the probability of measuring that particular Fock state. Let's compare the case of measuring at the output state $\left|0,1,0,1\right\rangle$: | B = (np.dot(U,U.T) * np.tanh(1))[:, [1,3]][[1,3]]
np.abs(Haf(B))**2 / np.cosh(1)**4
state.fock_prob([0,1,0,1]) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
For the measurement result $\left|2,0,0,0\right\rangle$: | B = (np.dot(U,U.T) * np.tanh(1))[:, [0,0]][[0,0]]
np.abs(Haf(B))**2 / (2*np.cosh(1)**4)
state.fock_prob([2,0,0,0]) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
For the measurement result $\left|1,1,0,0\right\rangle$: | B = (np.dot(U,U.T) * np.tanh(1))[:, [0,1]][[0,1]]
np.abs(Haf(B))**2 / np.cosh(1)**4
state.fock_prob([1,1,0,0]) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
For the measurement result $\left|1,1,1,1\right\rangle$, this corresponds to the full matrix $B$: | B = (np.dot(U,U.T) * np.tanh(1))
np.abs(Haf(B))**2 / np.cosh(1)**4
state.fock_prob([1,1,1,1]) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
For the measurement result $\left|0,0,0,0\right\rangle$, this corresponds to a **null** submatrix, which has a Hafnian of 1: | 1/np.cosh(1)**4
state.fock_prob([0,0,0,0]) | _____no_output_____ | Apache-2.0 | examples/GaussianBosonSampling.ipynb | cclauss/strawberryfields |
Pytorch: An automatic differentiation tool`Pytorch`λ₯Ό νμ©νλ©΄ 볡μ‘ν ν¨μμ λ―ΈλΆμ μμ½κ² + ν¨μ¨μ μΌλ‘ κ³μ°ν μ μμ΅λλ€!`Pytorch`λ₯Ό νμ©ν΄μ 볡μ‘ν μ¬μΈ΅ μ κ²½λ§μ νλ ¨ν λ, μ€μ°¨ν¨μμ λν νλΌλ―Έν°μ νΈλ―ΈλΆμΉλ₯Ό κ³μ°μ μμ½κ² μνν μ μμ΅λλ€! Pytorch 첫λ§λ¨μ°λ¦¬μκ² μλμ κ°μ κ°λ¨ν μ νμμ΄ μ£Όμ΄μ Έμλ€κ³ μκ°ν΄λ³ΌκΉμ?$$ y = wx $$ κ·Έλ¬λ©΄ $\frac{\partial y}{\partial w}$ μ μ΄λ»κ² κ³μ° ν μ μμκΉμ?μΌλ¨ μ§μ λ―ΈλΆμ ν΄λ³΄λ©΄$\frac{\partial y}{\part... | # λν¬1 / μ¬μ΄μ¦1 μ΄λ©° κ°μ 1*2 μΈ pytorch tensorλ₯Ό νλ λ§λλλ€.
x = torch.ones(1) * 2
# λν¬1 / μ¬μ΄μ¦1 μ΄λ©° κ°μ 1 μΈ pytorch tensorλ₯Ό νλ λ§λλλ€.
w = torch.ones(1, requires_grad=True)
y = w * x
y | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
νΈλ―ΈλΆ κ³μ°νκΈ°!pytorchμμλ λ―ΈλΆκ°μ κ³μ°νκ³ μΆμ ν
μμ `.backward()` λ₯Ό λΆμ¬μ£Όλ κ²μΌλ‘, ν΄λΉ ν
μ κ³μ°μ μ°κ²° λμ΄μλ ν
μ μ€ `gradient`λ₯Ό κ³μ°ν΄μΌνλ ν
μ(λ€)μ λν νΈλ―ΈλΆμΉλ€μ κ³μ°ν μ μμ΅λλ€. `requires_grad=True`λ₯Ό ν΅ν΄μ μ΄λ€ ν
μμ λ―ΈλΆκ°μ κ³μ°ν μ§ ν λΉν΄μ€ μ μμ΅λλ€. | y.backward() | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
νΈλ―ΈλΆκ° νμΈνκΈ°!`ν
μ.grad` λ₯Ό νμ©ν΄μ νΉμ ν
μμ gradient κ°μ νμΈν΄λ³Ό μ μμ΅λλ€. νλ² `w.grad`λ₯Ό νμ©ν΄μ `y` μ λν `w`μ νΈλ―ΈλΆκ°μ νμΈν΄λ³ΌκΉμ? | w.grad | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
κ·Έλ¬λ©΄ requires_grad = False μΈ κ²½μ°λ? | x.grad | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
`torch.nn`, Neural Network ν¨ν€μ§`pytorch`μλ μ΄λ―Έ λ€μν neural networkλ€μ λͺ¨λλ€μ ꡬνν΄ λμμ΅λλ€. κ·Έ μ€μ κ°μ₯ κ°λ¨νμ§λ§ μ λ§ μμ£Ό μ°μ΄λ `nn.Linear` μ λν΄ μμ보면μ `pytorch`μ `nn.Module`μ λν΄μ μμ보λλ‘ ν©μλ€. `nn.Linear` λμ보기`nn.Linear` μ μμ λ°°μ΄ μ ννκ· λ° λ€μΈ΅ νΌμ
νΈλ‘ λͺ¨λΈμ ν μΈ΅μ ν΄λΉνλ νλΌλ―Έν° $w$, $b$ λ₯Ό κ°μ§κ³ μμ΅λλ€. μμλ‘ μ
λ ₯μ dimension μ΄ 10μ΄κ³ μΆλ ₯μ dimension μ΄ 1μΈ `nn.Linear` λͺ¨λμ... | lin = nn.Linear(in_features=10, out_features=1)
for p in lin.parameters():
print(p)
print(p.shape)
print('\n') | Parameter containing:
tensor([[ 0.0561, 0.1509, 0.0586, -0.0598, -0.1934, 0.2985, -0.0112, 0.0390,
0.2597, -0.1488]], requires_grad=True)
torch.Size([1, 10])
Parameter containing:
tensor([-0.2357], requires_grad=True)
torch.Size([1])
| MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
`Linear` λͺ¨λλ‘ $y = Wx+b$ κ³μ°νκΈ°μ ννκ·μλ κ·Έλ¬μ§λ§, λ€μΈ΅ νΌμ
νΈλ‘ λͺ¨λΈλ νλμ λ μ΄μ΄λ μλμ μμμ κ³μ°νλ κ²μ κΈ°μ΅νμμ£ ?$$y = Wx+b$$`nn.Linear`λ₯Ό νμ©ν΄μ μ μμμ κ³μ°ν΄λ³ΌκΉμ?κ²μ°μ μ½κ² νκΈ° μν΄μ Wμ κ°μ λͺ¨λ 1.0 μΌλ‘ b λ 5.0 μΌλ‘ λ§λ€μ΄λκ² μ΅λλ€. | lin.weight.data = torch.ones_like(lin.weight.data)
lin.bias.data = torch.ones_like(lin.bias.data) * 5.0
for p in lin.parameters():
print(p)
print(p.shape)
print('\n')
x = torch.ones(3, 10) # rank2 tensorλ₯Ό λ§λλλ€. : mini batch size = 3
y_hat = lin(x)
print(y_hat.shape)
print(y_hat) | torch.Size([3, 1])
tensor([[15.],
[15.],
[15.]], grad_fn=<AddmmBackward>)
| MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
μ§κΈ 무μ¨μΌμ΄ μΌμ΄λκ±°μ£ ?>Q1. μ Rank 2 tensor λ₯Ό μ
λ ₯μΌλ‘ μ¬μ©νλμ? >A1. νμ΄ν μΉμ `nn` μ μ μλμ΄μλ ν΄λμ€λ€μ μ
λ ₯μ κ°μ₯ 첫λ²μ§Έ λλ©μ Όμ `λ°°μΉ μ¬μ΄μ¦`λ‘ ν΄μν©λλ€. >Q2. lin(x) λ λλ체 무μμΈκ°μ? >A2. νμ΄μ¬μ μ΅μνμ λΆλ€μ `object()` λ `object.__call__()`μ μ μλμ΄μλ ν¨μλ₯Ό μ€νμν€μ λ€λ κ²μ μμ€ν
λ°μ. νμ΄ν μΉμ `nn.Module`μ `__call__()`μ μ€λ²λΌμ΄λνλ ν¨μμΈ `forward()`λ₯Ό ꡬννλ κ²μ __κΆμ₯__ νκ³ μμ΅λλ€. μΌλ°μ μΌλ‘, `forward()... | def generate_samples(n_samples: int,
w: float = 1.0,
b: float = 0.5,
x_range=[-1.0,1.0]):
xs = np.random.uniform(low=x_range[0], high=x_range[1], size=n_samples)
ys = w * xs + b
xs = torch.tensor(xs).view(-1,1).float() # νμ΄ν μΉ nn.Modu... | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
Loss ν¨μλ? MSE!`pytorch`μμλ μμ£Ό μ°μ΄λ loss ν¨μλ€μ λν΄μλ 미리 ꡬνμ ν΄λμμ΅λλ€.μ΄λ² μ€μ΅μμλ __numpyλ‘ μ ννκ· λͺ¨λΈ λ§λ€κΈ°__ μμ μ¬μ©λλ MSE λ₯Ό μ€μ°¨ν¨μλ‘ μ¬μ©ν΄λ³ΌκΉμ? | criteria = nn.MSELoss()
loss = criteria(ys_hat, ys) | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
κ²½μ¬νκ°λ²μ νμ©ν΄μ νλΌλ―Έν° μ
λ°μ΄νΈνκΈ°!`pytorch`λ μ¬λ¬λΆλ€μ μν΄μ λ€μν optimizerλ€μ ꡬνν΄ λμμ΅λλ€. μΌλ¨μ κ°μ₯ κ°λ¨ν stochastic gradient descent (SGD)λ₯Ό νμ©ν΄ λ³ΌκΉμ? optimizerμ λ°λΌμ λ€μν μΈμλ€μ νμ©νμ§λ§ κΈ°λ³Έμ μΌλ‘ `params` μ `lr`μ μ§μ ν΄μ£Όλ©΄ λλ¨Έμ§λ optimizer λ§λ€ μλλ κ²μΌλ‘ μλ €μ§ μΈμλ€λ‘ optimizerμ μμ½κ² μμ±ν μ μμ΅λλ€. | opt = torch.optim.SGD(params=lin_model.parameters(), lr=0.01) | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
μμ§λ§μΈμ! opt.zero_grad()`pytorch`λ‘ νΈλ―ΈλΆμ κ³μ°νκΈ°μ μ, κΌ `opt.zero_grad()` ν¨μλ₯Ό μ΄μ©ν΄μ νΈλ―ΈλΆ κ³μ°μ΄ νμν ν
μλ€μ νΈλ―ΈλΆκ°μ μ΄κΈ°ν ν΄μ£Όλ κ²μ κΆμ₯λ립λλ€. | opt.zero_grad()
for p in lin_model.parameters():
print(p)
print(p.grad)
loss.backward()
opt.step()
for p in lin_model.parameters():
print(p)
print(p.grad) | Parameter containing:
tensor([[-0.5666]], requires_grad=True)
tensor([[-1.1548]])
Parameter containing:
tensor([0.6042], requires_grad=True)
tensor([-0.1280])
| MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
κ²½μ¬νκ°λ²μ νμ©ν΄μ μ΅μ νλΌλ―Έν°λ₯Ό μ°Ύμλ΄
μλ€! | def run_sgd(n_steps: int = 1000,
report_every: int = 100,
verbose=True):
lin_model = nn.Linear(in_features=1, out_features=1)
opt = torch.optim.SGD(params=lin_model.parameters(), lr=0.01)
sgd_losses = []
for i in range(n_steps):
ys_hat = lin_model(xs)
loss =... |
0th update: 0.8393566012382507
Parameter containing:
tensor([[0.1211]], requires_grad=True)
Parameter containing:
tensor([-0.1363], requires_grad=True)
100th update: 0.060856711119413376
Parameter containing:
tensor([[0.6145]], requires_grad=True)
Parameter containing:
tensor([0.4634], requires_grad=True)
200th u... | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
λ€λ₯Έ Optimizerλ μ¬μ©ν΄λ³ΌκΉμ?μμ
μκ°μ λ°°μ λ Adam μΌλ‘ μ΅μ νλ₯Ό νλ©΄ μ΄λ€κ²°κ³Όκ° λμ¬κΉμ? | def run_adam(n_steps: int = 1000,
report_every: int = 100,
verbose=True):
lin_model = nn.Linear(in_features=1, out_features=1)
opt = torch.optim.Adam(params=lin_model.parameters(), lr=0.01)
adam_losses = []
for i in range(n_steps):
ys_hat = lin_model(xs)
l... |
0th update: 1.2440284490585327
Parameter containing:
tensor([[0.4118]], requires_grad=True)
Parameter containing:
tensor([-0.4825], requires_grad=True)
100th update: 0.05024972930550575
Parameter containing:
tensor([[1.0383]], requires_grad=True)
Parameter containing:
tensor([0.2774], requires_grad=True)
200th up... | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
μ’ λ μμΈνκ² λΉκ΅ν΄λ³ΌκΉμ?`pytorch`μμ `nn.Linear`λ₯Ό λΉλ‘―ν λ§μ λͺ¨λλ€μ νΉλ³ν κ²½μ°κ° μλμ΄μ,λͺ¨λλ΄μ νλΌλ―Έν°κ° μμμ κ°μΌλ‘ __μ!__ μ΄κΈ°ν λ©λλ€. > "μ!" μ λν΄μλ μμ
μμ λ€λ£¨μ§ μμμ§λ§, νμ€ν νλ λ₯λ¬λμ΄ μ μλνκ² νλ μ€μν μμμ€μ νλμ
λλ€. Parameter initialization μ΄λΌκ³ λΆλ₯΄λ κΈ°λ²λ€μ΄λ©°, λλΆλΆμ `pytorch` λͺ¨λλ€μ κ°κ°μ λͺ¨λμ λ°λΌμ μΌλ°μ μΌλ‘ μ μλνλκ²μΌλ‘ μλ €μ Έμλ λ°©μμΌλ‘ νλΌλ―Έν°λ€μ΄ μ΄κΈ°ν λκ² μ½λ©λμ΄ μμ΅λλ€.κ·Έλμ λ§€ λ² λͺ¨λμ μμ±ν λλ§λ€ νλΌλ―Έν°μ μ΄κΈ°κ°... | sgd_losses = [run_sgd(verbose=False) for _ in range(50)]
sgd_losses = np.stack(sgd_losses)
sgd_loss_mean = np.mean(sgd_losses, axis=0)
sgd_loss_std = np.std(sgd_losses, axis=-0)
adam_losses = [run_adam(verbose=False) for _ in range(50)]
adam_losses = np.stack(adam_losses)
adam_loss_mean = np.mean(adam_losses, axis=0)
a... | _____no_output_____ | MIT | [Preliminary] 00 Linear regression with pytorch.ipynb | Junyoungpark/2021-lg-AI-camp |
Analyzing IMDB Data in Keras | # Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42) | Using TensorFlow backend.
| MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
1. Loading the dataThis dataset comes preloaded with Keras, so one simple command will get us training and testing data. There is a parameter for how many words we want to look at. We've set it at 1000, but feel free to experiment. | # Loading the data (it's preloaded in Keras)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)
print(x_train.shape)
print(x_test.shape) | (25000,)
(25000,)
| MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
2. Examining the dataNotice that the data has been already pre-processed, where all the words have numbers, and the reviews come in as a vector with the words that the review contains. For example, if the word 'the' is the first one in our dictionary, and a review contains the word 'the', then there is a 1 in the corr... | print(x_train[0])
print(y_train[0]) | [1, 11, 2, 11, 4, 2, 745, 2, 299, 2, 590, 2, 2, 37, 47, 27, 2, 2, 2, 19, 6, 2, 15, 2, 2, 17, 2, 723, 2, 2, 757, 46, 4, 232, 2, 39, 107, 2, 11, 4, 2, 198, 24, 4, 2, 133, 4, 107, 7, 98, 413, 2, 2, 11, 35, 781, 8, 169, 4, 2, 5, 259, 334, 2, 8, 4, 2, 10, 10, 17, 16, 2, 46, 34, 101, 612, 7, 84, 18, 49, 282, 167, 2, 2, 122, ... | MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
3. One-hot encoding the outputHere, we'll turn the input vectors into (0,1)-vectors. For example, if the pre-processed vector contains the number 14, then in the processed vector, the 14th entry will be 1. | # One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])
print(x_train.shape)
x_train[1] | (25000, 1000)
| MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
And we'll also one-hot encode the output. | # One-hot encoding the output
num_classes = 2
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
print(y_test.shape) | (25000, 2)
(25000, 2)
| MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
4. Building the model architectureBuild a model here using sequential. Feel free to experiment with different layers and sizes! Also, experiment adding dropout to reduce overfitting. | # TODO: Build the model architecture
model = Sequential()
model.add(Dense(128, input_dim = x_train.shape[1]))
model.add(Activation('relu'))
model.add(Dense(2))
model.add(Activation('softmax'))
# TODO: Compile the model using a loss function and an optimizer.
model.compile(loss = 'categorical_crossentropy', optimizer =... | _____no_output_____ | MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
5. Training the modelRun the model here. Experiment with different batch_size, and number of epochs! | # TODO: Run the model. Feel free to experiment with different batch sizes and number of epochs.
model.fit(x_train, y_train, 10000 , verbose = 0) | _____no_output_____ | MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
6. Evaluating the modelThis will give you the accuracy of the model, as evaluated on the testing set. Can you get something over 85%? | score = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: ", score[1]) | Accuracy: 0.85832
| MIT | 4. Deep Learning/IMDB_In_Keras.ipynb | Arwa-Ibrahim/ML_Nano_Projects |
Graded AssessmentIn this assessment you will write a full end-to-end training process using gluon and MXNet. We will train the LeNet-5 classifier network on the MNIST dataset. The network will be defined for you but you have to fill in code to prepare the dataset, train the network, and evaluate it's performance on a... | #Check CUDA version
!nvcc --version
#Install appropriate MXNet version
'''
For eg if CUDA version is 10.0 choose mxnet cu100mkl
where cu adds CUDA GPU support
and mkl adds Intel CPU Math Kernel Library support
'''
!pip install mxnet-cu101mkl gluoncv
from pathlib import Path
from mxnet import gluon, metric, autograd, i... | _____no_output_____ | MIT | Module_5_LeNet_on_MNIST (1).ipynb | vigneshb-it19/AWS-Computer-Vision-GluonCV |
--- Question 1 Prepare and the data and construct the dataloader* First, get the MNIST dataset from `gluon.data.vision.datasets`. Use* Don't forget the ToTensor and normalize Transformations. Use `0.13` and `0.31` as the mean and standard deviation respectively* Construct the dataloader with the batch size provide. Ens... | import os
from pathlib import Path
from mxnet.gluon.data.vision import transforms
import numpy as np
def get_mnist_data(batch=128):
"""
Should construct a dataloader with the MNIST Dataset with the necessary transforms applied.
:param batch: batch size for the DataLoader.
:type batch: int
... | _____no_output_____ | MIT | Module_5_LeNet_on_MNIST (1).ipynb | vigneshb-it19/AWS-Computer-Vision-GluonCV |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.