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 a basic TensorFlow Lite for Microcontrollers modelThis notebook demonstrates the process of training a 2.5 kB model using TensorFlow and converting it for use with TensorFlow Lite for Microcontrollers. Deep learning networks learn to model patterns in underlying data. Here, we're going to train a network to mode... | # Define paths to model files
import os
MODELS_DIR = 'models/'
if not os.path.exists(MODELS_DIR):
os.mkdir(MODELS_DIR)
MODEL_TF = MODELS_DIR + 'model.pb'
MODEL_NO_QUANT_TFLITE = MODELS_DIR + 'model_no_quant.tflite'
MODEL_TFLITE = MODELS_DIR + 'model.tflite'
MODEL_TFLITE_MICRO = MODELS_DIR + 'model.cc' | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Setup EnvironmentInstall Dependencies | ! pip install -q tensorflow==2 | [K |████████████████████████████████| 86.3MB 52kB/s
[K |████████████████████████████████| 450kB 46.2MB/s
[K |████████████████████████████████| 3.8MB 50.3MB/s
[?25h Building wheel for gast (setup.py) ... [?25l[?25hdone
| Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Set Seed for Repeatable Results | # Set a "seed" value, so we get the same random numbers each time we run this
# notebook for reproducible results.
# Numpy is a math library
import numpy as np
np.random.seed(1) # numpy seed
# TensorFlow is an open source machine learning library
import tensorflow as tf
tf.random.set_seed(1) # tensorflow global random ... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Import Dependencies | # Keras is TensorFlow's high-level API for deep learning
from tensorflow import keras
# Matplotlib is a graphing library
import matplotlib.pyplot as plt
# Math is Python's math library
import math | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Dataset 1. Generate DataThe code in the following cell will generate a set of random `x` values, calculate their sine values, and display them on a graph. | # Number of sample datapoints
SAMPLES = 1000
# Generate a uniformly distributed set of random numbers in the range from
# 0 to 2π, which covers a complete sine wave oscillation
x_values = np.random.uniform(
low=0, high=2*math.pi, size=SAMPLES).astype(np.float32)
# Shuffle the values to guarantee they're not in or... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
2. Add NoiseSince it was generated directly by the sine function, our data fits a nice, smooth curve.However, machine learning models are good at extracting underlying meaning from messy, real world data. To demonstrate this, we can add some noise to our data to approximate something more life-like.In the following ce... | # Add a small random number to each y value
y_values += 0.1 * np.random.randn(*y_values.shape)
# Plot our data
plt.plot(x_values, y_values, 'b.')
plt.show() | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
3. Split the DataWe now have a noisy dataset that approximates real world data. We'll be using this to train our model.To evaluate the accuracy of the model we train, we'll need to compare its predictions to real data and check how well they match up. This evaluation happens during training (where it is referred to as... | # We'll use 60% of our data for training and 20% for testing. The remaining 20%
# will be used for validation. Calculate the indices of each section.
TRAIN_SPLIT = int(0.6 * SAMPLES)
TEST_SPLIT = int(0.2 * SAMPLES + TRAIN_SPLIT)
# Use np.split to chop our data into three parts.
# The second argument to np.split is an... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Training 1. Design the ModelWe're going to build a simple neural network model that will take an input value (in this case, `x`) and use it to predict a numeric output value (the sine of `x`). This type of problem is called a _regression_. It will use _layers_ of _neurons_ to attempt to learn any patterns underlying ... | # We'll use Keras to create a simple model architecture
model_1 = tf.keras.Sequential()
# First layer takes a scalar input and feeds it through 8 "neurons". The
# neurons decide whether to activate based on the 'relu' activation function.
model_1.add(keras.layers.Dense(8, activation='relu', input_shape=(1,)))
# Final... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
2. Train the ModelOnce we've defined the model, we can use our data to _train_ it. Training involves passing an `x` value into the neural network, checking how far the network's output deviates from the expected `y` value, and adjusting the neurons' weights and biases so that the output is more likely to be correct th... | # Train the model on our training data while validating on our validation set
history_1 = model_1.fit(x_train, y_train, epochs=500, batch_size=64,
validation_data=(x_validate, y_validate)) | Train on 600 samples, validate on 200 samples
Epoch 1/500
600/600 [==============================] - 1s 971us/sample - loss: 0.6936 - mae: 0.6897 - val_loss: 0.6396 - val_mae: 0.6501
Epoch 2/500
600/600 [==============================] - 0s 50us/sample - loss: 0.5965 - mae: 0.6254 - val_loss: 0.5594 - val_mae: 0.6035
E... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
3. Plot Metrics **1. Mean Squared Error**During training, the model's performance is constantly being measured against both our training data and the validation data that we set aside earlier. Training produces a log of data that tells us how the model's performance changed over the course of the training process.The ... | # Draw a graph of the loss, which is the distance between
# the predicted and actual values during training and validation.
loss = history_1.history['loss']
val_loss = history_1.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, 'g.', label='Training loss')
plt.plot(epochs, val_loss, 'b', lab... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
The graph shows the _loss_ (or the difference between the model's predictions and the actual data) for each epoch. There are several ways to calculate loss, and the method we have used is _mean squared error_. There is a distinct loss value given for the training and the validation data.As we can see, the amount of los... | # Exclude the first few epochs so the graph is easier to read
SKIP = 50
plt.plot(epochs[SKIP:], loss[SKIP:], 'g.', label='Training loss')
plt.plot(epochs[SKIP:], val_loss[SKIP:], 'b.', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
From the plot, we can see that loss continues to reduce until around 200 epochs, at which point it is mostly stable. This means that there's no need to train our network beyond 200 epochs.However, we can also see that the lowest loss value is still around 0.155. This means that our network's predictions are off by an a... | plt.clf()
# Draw a graph of mean absolute error, which is another way of
# measuring the amount of error in the prediction.
mae = history_1.history['mae']
val_mae = history_1.history['val_mae']
plt.plot(epochs[SKIP:], mae[SKIP:], 'g.', label='Training MAE')
plt.plot(epochs[SKIP:], val_mae[SKIP:], 'b.', label='Validat... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
This graph of _mean absolute error_ tells another story. We can see that training data shows consistently lower error than validation data, which means that the network may have _overfit_, or learned the training data so rigidly that it can't make effective predictions about new data.In addition, the mean absolute erro... | # Calculate and print the loss on our test dataset
loss = model_1.evaluate(x_test, y_test)
# Make predictions based on our test dataset
predictions = model_1.predict(x_test)
# Graph the predictions against the actual values
plt.clf()
plt.title('Comparison of predictions and actual values')
plt.plot(x_test, y_test, 'b... |
200/1 [========================================================================================================================================================================================================================================================================================================================... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Oh dear! The graph makes it clear that our network has learned to approximate the sine function in a very limited way.The rigidity of this fit suggests that the model does not have enough capacity to learn the full complexity of the sine wave function, so it's only able to approximate it in an overly simplistic way. By... | model_2 = tf.keras.Sequential()
# First layer takes a scalar input and feeds it through 16 "neurons". The
# neurons decide whether to activate based on the 'relu' activation function.
model_2.add(keras.layers.Dense(16, activation='relu', input_shape=(1,)))
# The new second layer may help the network learn more comple... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
2. Train the Model We'll now train the new model. | history_2 = model_2.fit(x_train, y_train, epochs=500, batch_size=64,
validation_data=(x_validate, y_validate)) | Train on 600 samples, validate on 200 samples
Epoch 1/500
600/600 [==============================] - 0s 736us/sample - loss: 0.4245 - mae: 0.5529 - val_loss: 0.4310 - val_mae: 0.5678
Epoch 2/500
600/600 [==============================] - 0s 64us/sample - loss: 0.4056 - mae: 0.5462 - val_loss: 0.4138 - val_mae: 0.5548
E... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
3. Plot MetricsEach training epoch, the model prints out its loss and mean absolute error for training and validation. You can read this in the output above (note that your exact numbers may differ): ```Epoch 500/500600/600 [==============================] - 0s 51us/sample - loss: 0.0118 - mae: 0.0873 - val_loss: 0.01... | # Draw a graph of the loss, which is the distance between
# the predicted and actual values during training and validation.
loss = history_2.history['loss']
val_loss = history_2.history['val_loss']
epochs = range(1, len(loss) + 1)
# Exclude the first few epochs so the graph is easier to read
SKIP = 100
plt.figure(fi... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Great results! From these graphs, we can see several exciting things:* The overall loss and MAE are much better than our previous network* Metrics are better for validation than training, which means the network is not overfittingThe reason the metrics for validation are better than those for training is that valid... | # Calculate and print the loss on our test dataset
loss = model_2.evaluate(x_test, y_test)
# Make predictions based on our test dataset
predictions = model_2.predict(x_test)
# Graph the predictions against the actual values
plt.clf()
plt.title('Comparison of predictions and actual values')
plt.plot(x_test, y_test, 'b... |
200/1 [========================================================================================================================================================================================================================================================================================================================... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Much better! The evaluation metrics we printed show that the model has a low loss and MAE on the test data, and the predictions line up visually with our data fairly well.The model isn't perfect; its predictions don't form a smooth sine curve. For instance, the line is almost straight when `x` is between 4.2 and 5.2. I... | # Convert the model to the TensorFlow Lite format without quantization
converter = tf.lite.TFLiteConverter.from_keras_model(model_2)
model_no_quant_tflite = converter.convert()
# # Save the model to disk
open(MODEL_NO_QUANT_TFLITE, "wb").write(model_no_quant_tflite)
# Convert the model to the TensorFlow Lite format w... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
2. Compare Model Sizes | import os
model_no_quant_size = os.path.getsize(MODEL_NO_QUANT_TFLITE)
print("Model is %d bytes" % model_no_quant_size)
model_size = os.path.getsize(MODEL_TFLITE)
print("Quantized model is %d bytes" % model_size)
difference = model_no_quant_size - model_size
print("Difference is %d bytes" % difference) | Model is 2736 bytes
Quantized model is 2512 bytes
Difference is 224 bytes
| Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Our quantized model is only 224 bytes smaller than the original version, which only a tiny reduction in size! At around 2.5 kilobytes, this model is already so small that the weights make up only a small fraction of the overall size, meaning quantization has little effect.More complex models have many more weights, mea... | # Instantiate an interpreter for each model
model_no_quant = tf.lite.Interpreter(MODEL_NO_QUANT_TFLITE)
model = tf.lite.Interpreter(MODEL_TFLITE)
# Allocate memory for each model
model_no_quant.allocate_tensors()
model.allocate_tensors()
# Get the input and output tensors so we can feed in values and get the results
... | _____no_output_____ | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
We can see from the graph that the predictions for the original model, the converted model, and the quantized model are all close enough to be indistinguishable. This means that our quantized model is ready to use! Generate a TensorFlow Lite for Microcontrollers ModelConvert the TensorFlow Lite quantized model into a ... | # Install xxd if it is not available
!apt-get update && apt-get -qq install xxd
# Convert to a C source file
!xxd -i {MODEL_TFLITE} > {MODEL_TFLITE_MICRO}
# Update variable names
REPLACE_TEXT = MODEL_TFLITE.replace('/', '_').replace('.', '_')
!sed -i 's/'{REPLACE_TEXT}'/g_model/g' {MODEL_TFLITE_MICRO} | Get:1 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease [3,626 B]
Ign:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 InRelease
Hit:3 http://archive.ubuntu.com/ubuntu bionic InRelease
Get:4 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Hit:5 http... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
Deploy to a MicrocontrollerFollow the instructions in the [hello_world](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/hello_world) README.md for [TensorFlow Lite for MicroControllers](https://www.tensorflow.org/lite/microcontrollers/overview) to deploy this model on a specific mic... | # Print the C source file
!cat {MODEL_TFLITE_MICRO} | unsigned char g_model[] = {
0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, 0x33, 0x00, 0x00, 0x12, 0x00,
0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00,
0x00, 0x00, 0x18, 0x00, 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x60, 0x09, 0x00, 0x00, 0xa8, 0x02, 0x00, 0x00, 0x90, 0x02, 0x00, 0x... | Apache-2.0 | tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb | ErikGro/tensorflow |
pywikipathways and bridgedbpy[](https://colab.research.google.com/github/kozo2/pywikipathways/blob/main/docs/pywikipathways-and-bridgedbpy.ipynb)by Kozo Nishida and Alexander Picopywikipathways 0.0.2 bridgedbpy 0.0.2*WikiPathways* is a well-kno... | !pip install pywikipathways bridgedbpy
import pywikipathways as pwpw
import bridgedbpy as brdgdbp | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
Getting startedLets first check some of the most basic functions from each package. For example, here’s how you check to see which species are currently supported by WikiPathways: | org_names = pwpw.list_organisms()
org_names | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
You should see 30 or more species listed. This list is useful for subsequent queries that take an *organism* argument, to avoid misspelling.However, some function want the organism code, rather than the full name. Using bridgedbpy’s *getOrganismCode* function, we can get those: | org_names[14]
brdgdbp.get_organism_code(org_names[14]) | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
Identifier System Names and CodesEven more obscure are the various datasources providing official identifiers and how they are named and coded. Fortunately, BridgeDb defines these clearly and simply. And WikiPathways relies on these BridgeDb definitions.For example, this is how we find the system code for Ensembl: | brdgdbp.get_system_code("Ensembl") | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
It’s “En”! That’s simple enough. But some are less obvious… | brdgdbp.get_system_code("Entrez Gene") | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
It’s “L” because the resource used to be named “Locus Link”. Sigh… Don’t try to guess these codes. Use this function from BridgeDb (above) to get the correct code. By the way, all the systems supported by BridgeDb are here: https://github.com/bridgedb/datasources/blob/main/datasources.tsv How to use bridgedbpy with pyw... | tnf_pathways = pwpw.find_pathway_ids_by_xref('TNF', brdgdbp.get_system_code('HGNC'))
tnf_pathways | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
2. Getting all the genes from a pathway as Ensembl identifiers: | pwpw.get_xref_list('WP554', brdgdbp.get_system_code('Ensembl')) | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
3. Getting all the metabolites from a pathway as ChEBI identifiers: | pwpw.get_xref_list('WP554', brdgdbp.get_system_code('ChEBI')) | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
Other tipsAnd if you ever find yourself with a system code, e.g., from a pywikipathways return result and you’re not sure what it is, then you can use this function: | brdgdbp.get_full_name('Ce') | _____no_output_____ | MIT | docs/pywikipathways-and-bridgedbpy.ipynb | kozo2/pyWikiPathways |
Trainer> Implementation of torch-based model trainers. | #hide
from nbdev.showdoc import *
from fastcore.nb_imports import *
from fastcore.test import * | _____no_output_____ | Apache-2.0 | nbs/trainer.ipynb | sparsh-ai/recohut |
PL Trainer> Implementation of trainer for training PyTorch Lightning models. | #export
from typing import Any, Iterable, List, Optional, Tuple, Union, Callable
import os
import os.path as osp
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
#export
def pl_trainer(model, datamodule, max_epochs=10,... | _____no_output_____ | Apache-2.0 | nbs/trainer.ipynb | sparsh-ai/recohut |
Example | class Args:
def __init__(self):
self.data_dir = '/content/data'
self.min_rating = 4
self.num_negative_samples = 99
self.min_uc = 5
self.min_sc = 5
self.val_p = 0.2
self.test_p = 0.2
self.num_workers = 2
self.normalize = False
self.batch... | GPU available: False, used: False
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
| Name | Type | Params
-------------------------------------------------
0 | user_embedding | Embedding | 120 K
1 | item_embedding | Embedding | 62.5 K
2 | user_embedding_gmf | E... | Apache-2.0 | nbs/trainer.ipynb | sparsh-ai/recohut |
Traditional Torch Trainers v1 | # dataset
from recohut.datasets.movielens import ML1mRatingDataset
# models
from recohut.models.afm import AFM
from recohut.models.afn import AFN
from recohut.models.autoint import AutoInt
from recohut.models.dcn import DCN
from recohut.models.deepfm import DeepFM
from recohut.models.ffm import FFM
from recohut.models... | [01;34m/content/chkpt[00m
├── [669K] AFM.pt
├── [ 39M] AFN.pt
├── [1.5M] AutoInt.pt
├── [640K] DCN.pt
├── [676K] DeepFM.pt
├── [355K] FFM.pt
├── [666K] FM.pt
├── [363K] FNFM.pt
├── [636K] FNN.pt
├── [1.3M] HOFM.pt
├── [ 41K] LR.pt
├── [636K] NCF.pt
├── [2.5M] NFM.pt
├── [1.2M] PNN.pt
├── [676K] WideAnd... | Apache-2.0 | nbs/trainer.ipynb | sparsh-ai/recohut |
v2**References:-**1. https://nbviewer.org/github/CS-512-Recsys/Recsys/blob/main/nbs/basic_implementation.ipynb | !pip install -q wandb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
import os
import copy
import random
from pathlib import Path
from collections import defaultdict
from argparse import Namespace
from joblib import dump, ... | 11%|█ | 11/100 [00:00<00:01, 50.86it/s] | Apache-2.0 | nbs/trainer.ipynb | sparsh-ai/recohut |
Conceptual descriptionAs people interact, they tend to become more alike in their beliefs, attitudes and behaviour. In "The Dissemination of Culture: A Model with Local Convergence and Global Polarization" (1997), Robert Axelrod presents an agent-based model to explain cultural diffusion. Analogous to Schelling's segr... | import random
import numpy as np
from mesa import Model, Agent
import mesa.time as time
from mesa.time import RandomActivation
from mesa.space import SingleGrid
from mesa.datacollection import DataCollector
class CulturalDiff(Model):
"""
Model class for the Schelling segregation model.
Parameters
... | _____no_output_____ | BSD-3-Clause | src/old_exams/exam/Cultural Diffusion v3_Bugs.ipynb | lyoussifou/EPA1324_open |
Visualization Static imagesVisualization of this model are static images. A visualization after initialization, after 20 steps, after 50 steps, and after 200 steps is presented. After initialization | model = CulturalDiff(seed=123456789)
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import seaborn as sns
import pandas as pd
def plot_model(model, ax):
grid = np.zeros((model.height, model.width, 4))
for (cell, i, j) in model.grid.coord_iter():
color = [0,0,0,0] #in case not ever... | _____no_output_____ | BSD-3-Clause | src/old_exams/exam/Cultural Diffusion v3_Bugs.ipynb | lyoussifou/EPA1324_open |
After 20 steps | for i in range(20):
model.step()
fig, ax = plt.subplots()
plot_model(model, ax)
plt.show() | _____no_output_____ | BSD-3-Clause | src/old_exams/exam/Cultural Diffusion v3_Bugs.ipynb | lyoussifou/EPA1324_open |
After 50 steps | for i in range(30):
model.step()
fig, ax = plt.subplots()
plot_model(model, ax)
plt.show() | _____no_output_____ | BSD-3-Clause | src/old_exams/exam/Cultural Diffusion v3_Bugs.ipynb | lyoussifou/EPA1324_open |
After 200 steps | for i in range(150):
model.step()
fig, ax = plt.subplots()
plot_model(model, ax)
plt.show() | _____no_output_____ | BSD-3-Clause | src/old_exams/exam/Cultural Diffusion v3_Bugs.ipynb | lyoussifou/EPA1324_open |
SUPERVISED MACHINE LEARNING (LINEAR REGRESSION) Author-Neeraj Lalwani Importing important libraries | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Importing dataset | Data = pd.read_csv("marks.csv")
print("Data is successfully imported") | Data is successfully imported
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
First 7 records | Data.head(7) | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Last 7 records | Data.tail(7) | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Using describe() function to see count, mean, std, minimum, percentiles & maximum. | Data.describe() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Using info() function get information about the data | Data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 25 entries, 0 to 24
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Hours 25 non-null float64
1 Scores 25 non-null int64
dtypes: float64(1), int64(1)
memory usage: 528.0 bytes
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Visualizing Data. Ploting box plot | plt.boxplot(Data)
plt.show() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Ploting scatter plot | plt.xlabel('Hours',fontsize=15)
plt.ylabel('Scores',fontsize=15)
plt.title('Hours studied vs Score', fontsize=10)
plt.scatter(Data.Hours,Data.Scores,color='red',marker='*')
plt.show() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
The plots show positive linear relation between 'Hours' and 'Scores' | X = Data.iloc[:,:-1].values
Y = Data.iloc[:,1].values | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Preparing data and splitting into train and test sets. We are splitting our data using 80:20 rule(Pareto principle) | from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,random_state = 0,test_size=0.2)
print("X train.shape =", X_train.shape)
print("Y train.shape =", Y_train.shape)
print("X test.shape =", X_test.shape)
print("Y test.shape =", Y_test.shape)
| X train.shape = (20, 1)
Y train.shape = (20,)
X test.shape = (5, 1)
Y test.shape = (5,)
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Training the model. | from sklearn.linear_model import LinearRegression
linreg=LinearRegression() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Fitting Training data | linreg.fit(X_train,Y_train)
print("Training our algorithm is finished")
print("B0 =",linreg.intercept_,"\nB1 =",linreg.coef_) | B0 = 2.018160041434662
B1 = [9.91065648]
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
B0 = Intercept & Slope = B1 Plotting the regression line | Y0 = linreg.intercept_ + linreg.coef_*X_train | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Plotting training data | plt.scatter(X_train,Y_train,color='red',marker='*')
plt.plot(X_train,Y0,color='red')
plt.xlabel("Hours",fontsize=15)
plt.ylabel("Scores",fontsize=15)
plt.title("Regression line(Train set)",fontsize=10)
plt.show() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Test data | Y_pred=linreg.predict(X_test)##predicting the Scores for test data
print(Y_pred) | [16.88414476 33.73226078 75.357018 26.79480124 60.49103328]
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Plotting test data | plt.plot(X_test,Y_pred,color='red')
plt.scatter(X_test,Y_test,color='red',marker='*')
plt.xlabel("Hours",fontsize=15)
plt.ylabel("Scores",fontsize=15)
plt.title("Regression line(Test set)",fontsize=10)
plt.show() | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Comparing actual vs predicted scores | Y_test1 = list(Y_test)
prediction=list(Y_pred)
df_compare = pd.DataFrame({ 'Actual':Y_test1,'Result':prediction})
df_compare | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
ACCURACY OF THE MODEL Goodness of fit test | from sklearn import metrics
metrics.r2_score(Y_test,Y_pred) | _____no_output_____ | MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Above 94% indicates that above model is a good fit Predicting the Error | from sklearn.metrics import mean_squared_error,mean_absolute_error
MSE = metrics.mean_squared_error(Y_test,Y_pred)
root_E = np.sqrt(metrics.mean_squared_error(Y_test,Y_pred))
Abs_E = np.sqrt(metrics.mean_squared_error(Y_test,Y_pred))
print("Mean Squared Error = ",MSE)
print("Root Mean Squared Error = ",root_E)
pri... | Mean Squared Error = 21.598769307217456
Root Mean Squared Error = 4.647447612100373
Mean Absolute Error = 4.647447612100373
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Predicting the score for 9.25 hours | Prediction_score = linreg.predict([[9.25]])
print("predicted score for a student studying 9.25 hours :",Prediction_score) | predicted score for a student studying 9.25 hours : [93.69173249]
| MIT | TASK_1_Supervised ML/Task_1_supervised_ml.ipynb | njlalwani/TSF |
Imports | import numpy as np
import matplotlib.pyplot as plt
%tensorflow_version 2.x
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, LSTM, GRU, SimpleRNN, RepeatVector, Input
from keras import backend as K
from keras.utils.vis_utils import p... | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Load data | !git clone https://github.com/luisferuam/DLFBT-LAB
f = open('DLFBT-LAB/data/el_quijote.txt', 'r')
quijote = f.read()
f.close()
print(len(quijote)) | 1038397
| MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Input/output sequences | quijote_x = quijote[:-1]
quijote_y = quijote[1:] | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Some utility functions | def one_hot_encoding(data):
symbols = np.unique(data)
char_to_ix = {s: i for i, s in enumerate(symbols)}
ix_to_char = {i: s for i, s in enumerate(symbols)}
data_numeric = np.zeros(data.shape)
for s in symbols:
data_numeric[data == s] = char_to_ix[s]
one_hot_values = np.array(list(ix_to_char.keys()... | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Batches for training and test | batch_size = 32
seq_len = 50
longitud = len(quijote_x) // batch_size
print(longitud)
print(longitud*batch_size)
qx = [quijote_x[i*(batch_size+longitud):(i+1)*(batch_size+longitud)] for i in range(batch_size)]
qy = [quijote_y[i*(batch_size+longitud):(i+1)*(batch_size+longitud)] for i in range(batch_size)]
xs_one_hot, ys... | 20128
32
629.0
| MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Training/test partition | print(xs_one_hot.shape)
print(ys_one_hot.shape)
print(xs_sparse.shape)
print(ys_sparse.shape)
ntrain = int(num_batches*0.75)*batch_size
xs_one_hot_train = xs_one_hot[:ntrain]
ys_one_hot_train = ys_one_hot[:ntrain]
xs_sparse_train = xs_sparse[:ntrain]
ys_sparse_train = ys_sparse[:ntrain]
xs_one_hot_test = xs_one_hot[... | (20128, 50, 88)
(20128, 50, 88)
(20128, 50)
(20128, 50)
(15072, 50, 88)
(5056, 50, 88)
| MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Function to evaluate the model on test data | def evaluate_network(model, x, y, batch_size):
mean_loss = []
mean_acc = []
for i in range(0, x.shape[0], batch_size):
batch_data_x = x[i:i+batch_size, :, :]
batch_data_y = y[i:i+batch_size, :, :]
loss, acc = model.test_on_batch(batch_data_x, batch_data_y)
mean_loss.append(loss)
mean_acc.appe... | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Function that copies the weigths from ``source_model`` to ``dest_model`` | def copia_pesos(source_model, dest_model):
for source_layer, dest_layer in zip(source_model.layers, dest_model.layers):
dest_layer.set_weights(source_layer.get_weights()) | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Function that samples probabilities from model | def categorical(p):
return (p.cumsum(-1) >= np.random.uniform(size=p.shape[:-1])[..., None]).argmax(-1) | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Function that generates text | def genera_texto(first_char, num_chars):
texto = "" + first_char
next_char = first_char
next_one_hot = np.zeros(vocab_len)
next_one_hot[char_to_ix[next_char]] = 1.
next_one_hot = next_one_hot[None, None, :]
for i in range(num_chars):
probs = model2.predict_on_batch(next_one_hot)
next_ix = categori... | _____no_output_____ | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Network definition | K.clear_session()
nunits = 200
model1 = Sequential()
#model1.add(SimpleRNN(nunits, batch_input_shape=(batch_size, seq_len, vocab_len),
# return_sequences=True, stateful=True, unroll=True))
model1.add(LSTM(nunits, batch_input_shape=(batch_size, seq_len, vocab_len),
... | WARNING:tensorflow:Layer lstm will not use cuDNN kernel since it doesn't meet the cuDNN kernel criteria. It will use generic GPU kernel as fallback when running on GPU
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
... | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Network that generates text | model2 = Sequential()
#model2.add(SimpleRNN(nunits, batch_input_shape=(1, 1, vocab_len),
# return_sequences=True, stateful=True, unroll=True))
model2.add(LSTM(nunits, batch_input_shape=(1, 1, vocab_len),
return_sequences=True, stateful=True, unroll=True))
mod... | WARNING:tensorflow:Layer lstm_1 will not use cuDNN kernel since it doesn't meet the cuDNN kernel criteria. It will use generic GPU kernel as fallback when running on GPU
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #... | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Training | #learning_rate = 0.5 # Probar entre 0.05 y 5
#clip = 0.005 # Probar entre 0.0005 y 0.05
learning_rate = 0.5
clip = 0.002
#model1.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=learning_rate, clipvalue=clip), metrics=['accuracy'])
model1.compile(loss='categorical_crossentropy... | Training epoch: 1 / 500, loss = 2.506721, acc = 0.284691, test loss = 2.121773, test acc = 0.360455 >>> eEmVQQdionbta, pnen que moszaros gasmami mpre, a so oEsr, enal quavo a ebalvén la veridé stecarer e er lue cecdo den estotada se erchon que, dediion encar domo paruel pebrellias, cána ton cha motose
Training epoch... | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Plots | plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.plot(model1_loss, label="train")
plt.plot(model1_loss_test, label="test")
plt.grid(True)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.title('loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(model1_acc, label="train")
plt.plot(model1_acc_test, label="test")
plt.grid(... | A Míos! Pero y dejar la ignora señora mía, ni lo hubo musiéremos de compasados, avinto y extraña:
Cancho caí-; y me fueran sin ser amigo más término, efecto mucho del tomalaría Carna. Reído, estuviera un otra eso ne sea empresas y agora y al cual dijo:
-Pues salió, y tenido subía la pendimicas, con presenci... | MIT | DLFBT/recurrent_neural_networks/text_generation_quijote.ipynb | luisferuam/luisferuam.github.io |
Image GradientsGoalIn this notebook, we will learn to:- Find Image gradients, edges etc- We will see following functions : **cv2.Sobel()**, **cv2.Scharr()**, **cv2.Laplacian()** etc**Theory**OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and Laplacian. We will see each one of them. | #import required modeules
import cv2
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | 09_imageGradient.ipynb | fneema/Image_Processing |
**1. Sobel and Scharr Derivatives**Sobel operators is a joint Gausssian smoothing plus differentiation operation, so it is more resistant to noise. You can specify the direction of derivatives to be taken, vertical or horizontal (by the arguments, yorder and xorder respectively). You can also specify the size of kernel... |
img = cv2.imread('gausian.jpg',0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
plt.subplot(2,2,1),plt.imshow(img,cmap = 'gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(laplacian,cmap... | _____no_output_____ | MIT | 09_imageGradient.ipynb | fneema/Image_Processing |
**Note:**If you want to detect both edges, better option is to keep the output datatype to some higher forms, like cv2.CV_16S, cv2.CV_64F etc, take its absolute value and then convert back to cv2.CV_8U. | img = cv2.imread('gausian.jpg',0)
# Output dtype = cv2.CV_8U
sobelx8u = cv2.Sobel(img,cv2.CV_8U,1,0,ksize=5)
# Output dtype = cv2.CV_64F. Then take its absolute and convert to cv2.CV_8U
sobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
abs_sobel64f = np.absolute(sobelx64f)
sobel_8u = np.uint8(abs_sobel64f)
plt.subpl... | _____no_output_____ | MIT | 09_imageGradient.ipynb | fneema/Image_Processing |
Simplex Example 1 - Author: Mohit S. Chauhan - Date: Dec 6, 2018 In this example, random samples are generated uniformly inside a 2-D simplex. Import the necessary libraries. Here we import standard libraries such as numpy and matplotlib, but also need to import the Simplex class from UQpy. | from UQpy.SampleMethods import Simplex
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | example/SampleMethods/Simplex/Simplex_Example1.ipynb | shellshocked2003/UQpy |
Define an array of 3 points in 2-D, which will be coordinates of vertex of simplex. | vertex = np.array([[0, 0], [0.5, 1], [1, 0]]) | _____no_output_____ | MIT | example/SampleMethods/Simplex/Simplex_Example1.ipynb | shellshocked2003/UQpy |
Use Simplex class in SampleMethods module to generate unioformly distributed sample. This class needs two input, i.e. nodes and nsamples. Nodes is the vertex of simplex and nsamples is the number of new samples to be generated. In this example, we are generating ten new samples inside our simplex. | x = Simplex(nodes=vertex, nsamples=10) | _____no_output_____ | MIT | example/SampleMethods/Simplex/Simplex_Example1.ipynb | shellshocked2003/UQpy |
Figure shows the 2-D simplex and new samples generated using Simplex class. | plt.plot(np.array([0, 0.5, 1, 0]), np.array([0, 1, 0, 0]), color='blue')
plt.scatter(x.samples[:, 0], x.samples[:, 1], color='red')
plt.show() | _____no_output_____ | MIT | example/SampleMethods/Simplex/Simplex_Example1.ipynb | shellshocked2003/UQpy |
User can also define a Simplex object using vertices and generate samples using 'run' method. | y = Simplex(nodes=vertex)
y.run(nsamples=5) | _____no_output_____ | MIT | example/SampleMethods/Simplex/Simplex_Example1.ipynb | shellshocked2003/UQpy |
MSEplots on PYPI: pip install MSEplots-pkg----------msed_plots(pressure,temperature,mixing_ratio,h0_std,ensemble_size,ent_rate,entrain=Flase) - pressure: vertical profile of pressure, array-like - temperature: vertical profile of temperature, array-like - specific humidity: vertical profile of specific humi... | import numpy as np
from siphon.simplewebservice.wyoming import WyomingUpperAir
from datetime import datetime
from MSEplots import plots as mpt
# reading data prociding vertical profiles of T, Td, pressure and height
date = datetime(2018, 11, 24, 12)
station = 'MFL'
station = 'SKBG'
df = WyomingUpperAir.request_data(da... | _____no_output_____ | MIT | MSEplots-pkg_demo.ipynb | brianmapes/MSEplot |
* Get the dataset from the Stata Press publishing house on their website.* This gives a pandas series of the RGNP, and the index annotates the dates. | dta = pd.read_stata('https://www.stata-press.com/data/r14/rgnp.dta').iloc[1:]
dta.index = pd.DatetimeIndex(dta.date, freq='QS')
dta_hamilton = dta.rgnp | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* Domestic recessions and expansions model.* The model will include transition probabilities between these two regimes and predict probabilities of expansion or recession at each time point. | # Plot the data
dta_hamilton.plot(title='Growth rate of Real GNP', figsize=(16, 6)) | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* Fit the 4th order Markov switching model.* Specify two regimes. * Get the model fitted via maximum likelihood estimation to the RGNP data.* Set switching_ar=False because the statsmodels implementation defaults toswitching autoregressive coefficients. | # Fit the model
mod_hamilton = sm.tsa.MarkovAutoregression(dta_hamilton, k_regimes=2, order=4, switching_ar=False)
res_hamilton = mod_hamilton.fit() | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* See the regime transition parameters at the bottom of the same output. | print(res_hamilton.summary()) | Markov Switching Model Results
================================================================================
Dep. Variable: rgnp No. Observations: 131
Model: MarkovAutoregression Log Likelihood -181.... | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* See the lengths of recession and expansion.* The output array is in financial quarters.* Therefore, a recession is expected to take about four quarters (1 year) and an expansion 10 quarters (two and a half years). | res_hamilton.expected_durations | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* Plot the probability of recession at each point in time. | from pandas_datareader.data import DataReader
from datetime import datetime
usrec = DataReader('USREC', 'fred', start=datetime(1947, 1, 1), end=datetime(2013, 4, 1)) | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* This gives a DataFrame in which recessions are indicated. * Here are the first five rows.* In the first five rows, there was no recession according to the National Bureau of Economic Research (NBER) indicators. | usrec.head() | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* Plot NBER recession indicators against the model regime predictions.* This gives actual recession data against model predictions. | _, ax = plt.subplots(1, figsize=(16, 6))
ax.plot(res_hamilton.filtered_marginal_probabilities[0])
ax.fill_between(
usrec.index, 0, 1, where=usrec['USREC'].values,
color='gray', alpha=0.3
)
ax.set(
xlim=(dta_hamilton.index[4], dta_hamilton.index[-1]),
ylim=(0, 1),
title='Filtered probability of reces... | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML |
* See there seems to be quite a good match between the model predictions andactual recession indicators. | _____no_output_____ | MIT | Probabilistic Models for TS/Markov Switching Autoregression Model.ipynb | thirasit/Time-series-analysis-with-ML | |
HRF downsamplingThis short notebook is why (often) we have to downsample our predictors after convolution with an HRF. | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from nistats.hemodynamic_models import glover_hrf
%matplotlib inline | _____no_output_____ | MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
First, let's define our data. Suppose we did an experiment where we show subjects images for 4 seconds. The onset of the stimuli we're drawn semi-randomly: every 15 seconds but +/- 3 to 5 seconds. In total, the experiment lasted 5 minutes. The fMRI data we acquired during the experiment had a TR of 2 seconds. | TR = 2 # seconds
time_exp = 5*60 # seconds
number_of_events = 10
duration_of_events = 4
onsets_sec = np.arange(0, time_exp, 15) + np.random.uniform(3, 5, 20)
onsets_sec = np.round(onsets_sec, 3)
print("Onset events: %s" % (onsets_sec,)) | Onset events: [ 4.404 18.533 33.223 48.438 64.592 78.842 94.015 109.126 123.067
138.108 154.15 169.913 184.614 199.094 213.121 229.443 243.457 259.559
274.793 289.33 ]
| MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
As you can see, the onsets are not neatly synchronized to the time that we acquired the different volumes of our fMRI data, which are (with a TR of 2): `[0, 2, 4, 6, ..., 298]` seconds. In other words, the data (onsets) of our experimental paradigm are on a different scale (i.e., with a precision of milliseconds) than ... | stim_vector = np.zeros(time_exp * 1000)
print("Length of stim vector: %i" % stim_vector.size) | Length of stim vector: 300000
| MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
Now, let's convert our onsets to milliseconds: | onsets_msec = onsets_sec * 1000 | _____no_output_____ | MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
Now we can define within our `stim_vector` when each onset happened. Importantly, let's assume that each stimulus lasted 4 seconds. | for onset in onsets_msec:
onset = int(onset)
stim_vector[onset:(onset+duration_of_events*1000)] = 1 | _____no_output_____ | MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
Alright, let's plot it: | plt.plot(stim_vector)
plt.xlim(0, time_exp*1000)
plt.xlabel('Time (milliseconds)')
plt.ylabel('Activity (A.U.)')
sns.despine()
plt.show() | _____no_output_____ | MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
Sweet, now let's define an HRF: | hrf = glover_hrf(tr=TR, time_length=32, oversampling=TR*1000)
hrf = hrf / hrf.max()
plt.plot(hrf)
plt.xlabel('Time (milliseconds)')
plt.ylabel('Activity (A.U.)')
sns.despine()
plt.show() | _____no_output_____ | MIT | downsampling_hrf.ipynb | lukassnoek/random_notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.