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 |
|---|---|---|---|---|---|
Methods | # selecting which set to be used 1-8
# in order to combine them all assign set number to 9
def select_set(dataframe,setNumber):
if setNumber == 9:
dataframe2 = dataframe[dataframe.essay_set ==1]
texts = dataframe2['essay']
scores = dataframe2['domain1_score']
scores = scores.apply(la... | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Dataset selection | # 1-8
# 9:all sets combined
texts, scores = select_set(dataframe,1)
get_hist_avg(scores,5)
X_train, X_test, y_train, y_test, data = data_prepare(texts,scores) | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Regression Analysis | print('Testing for Linear Regression \n')
lin_regression(X_train,y_train,X_test,y_test)
print('Testing for Adaboost Regression \n')
adaBoost_reg(X_train,y_train,X_test,y_test) | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Dataset selection 2 | # 1-8
# 9:all sets combined
texts, scores = select_set_classification(dataframe,1)
X_train, X_test, y_train, y_test, data = data_prepare(texts,scores) | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Classification analysis | a=[0.1,1,10,100,500,1000]
for b in a:
clf = svm.SVC(C=b, gamma=0.00001)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print (b)
print (clf.score(X_test,y_test))
print (np.mean(cross_val_score(clf, X_train, y_train, cv=3)))
clf = svm.SVC(C=100, gamma=0.00001)
clf.fit(X_train, y_train)
... | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Data Analysis | sns.countplot(scores)
zero = data[(data["Character_Count"] > 0) & (scores == 0)]
one = data[(data["Character_Count"] > 0) & (scores == 1)]
two = data[(data["Character_Count"] > 0) & (scores == 2)]
sns.distplot(zero["Character_Count"], bins=10, color='r')
sns.distplot(one["Character_Count"], bins=10, color='g')
sns.dist... | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Hello SegmentationA very basic introduction to using segmentation models with OpenVINO.We use the pre-trained [road-segmentation-adas-0001](https://docs.openvinotoolkit.org/latest/omz_models_model_road_segmentation_adas_0001.html) model from the [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). ADA... | import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
from openvino.inference_engine import IECore
sys.path.append("../utils")
from notebook_utils import segmentation_map_to_image | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
Load the Model | ie = IECore()
net = ie.read_network(
model="model/road-segmentation-adas-0001.xml")
exec_net = ie.load_network(net, "CPU")
output_layer_ir = next(iter(exec_net.outputs))
input_layer_ir = next(iter(exec_net.input_info)) | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
Load an ImageA sample image from the [Mapillary Vistas](https://www.mapillary.com/dataset/vistas) dataset is provided. | # The segmentation network expects images in BGR format
image = cv2.imread("data/empty_road_mapillary.jpg")
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_h, image_w, _ = image.shape
# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = net.input_info[input_layer_ir].tensor_desc.dims
# Ope... | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
Do Inference | # Run the infernece
result = exec_net.infer(inputs={input_layer_ir: input_image})
result_ir = result[output_layer_ir]
# Prepare data for visualization
segmentation_mask = np.argmax(result_ir, axis=1)
plt.imshow(segmentation_mask[0]) | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
Prepare Data for Visualization | # Define colormap, each color represents a class
colormap = np.array([[68, 1, 84], [48, 103, 141], [53, 183, 120], [199, 216, 52]])
# Define the transparency of the segmentation mask on the photo
alpha = 0.3
# Use function from notebook_utils.py to transform mask to an RGB image
mask = segmentation_map_to_image(segme... | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
Visualize data | # Define titles with images
data = {"Base Photo": rgb_image, "Segmentation": mask, "Masked Photo": image_with_mask}
# Create subplot to visualize images
f, axs = plt.subplots(1, len(data.items()), figsize=(15, 10))
# Fill subplot
for ax, (name, image) in zip(axs, data.items()):
ax.axis('off')
ax.set_title(nam... | _____no_output_____ | Apache-2.0 | notebooks/003-hello-segmentation/003-hello-segmentation.ipynb | MilanaShhanukova/openvino_notebooks |
TD - Implémentation des arbres en POOOn va dans ce TD créer une classe arbre binaire qui va nous permettre d'implémenter cette structure de données avec toutes ses caractéristiques.On se souvient du cours sur les arbres https://pixees.fr/informatiquelycee/n_site/nsi_term_structDo_arbre.html dans lequel on définit le n... | class ArbreBinaire:
def __init__(self, valeur): #un arbre est un noeud contenant une valeur et deux enfants gauche et droit
self.valeur = valeur #le noeud contient la valeur passée en paramètre
self.enfant_gauche = None #l'enfant gauche est vide au départ
self.enfant_droit... | _____no_output_____ | MIT | .ipynb_checkpoints/TD-ImplementationArbreBinaire-checkpoint.ipynb | egouello/TermNSI |
Il est important de comprendre comment la structure de donnée est implémentée : un arbre est défini par une valeur et deux sous arbres gauches et droits qui sont tous les deux initialiés à None au démarrage.Lors de l'insertion d'une valeur à gauche ou à droite, on crée un nouvel arbre que l'on insère à la racine du sou... | arbre=ArbreBinaire(3)
arbre.insert_gauche(1)
arbre.insert_gauche(2) #on insère 2 à gauche, la valeur 1 se décale à gauche du 2
print(arbre) | (((None)1(None))2(None))3(None)
| MIT | .ipynb_checkpoints/TD-ImplementationArbreBinaire-checkpoint.ipynb | egouello/TermNSI |
Exercice 2Écrire le code permettant de créer l'arbre suivantVoila le début du code ci-dessous pour vous aider à démarrer... | arbre=ArbreBinaire("A")
arbre.insert_gauche("B")
arbreg=arbre.get_gauche()
arbreg.insert_gauche("C") #les deux lignes précédentes peuvent-être abbrégées en arbre.get_gauche().insert_gauche("C")
# à suivre...
print(arbre) | (((None)C(None))B(None))A(None)
| MIT | .ipynb_checkpoints/TD-ImplementationArbreBinaire-checkpoint.ipynb | egouello/TermNSI |
Chapter 7 - Exercise 3: Tips Cho dữ liệu tips có sẵn trong seaborn library. Hãy vẽ những biểu đồ theo yêu cầu, và đối chiếu với kết quả: | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
# Load dữ liệu tips có sẵn trong seaborn library
#total_bill: Total bill (cost of the meal), including tax, in US dollars
#tip: Tip (gratuity) in US dollars
#sex: Sex of person paying for the meal (0=male, 1=female)
#smoke... | _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <class 'pandas.core.frame.DataFrame'>RangeIndex: 244 entries, 0 to 243Data columns (total 7 columns):total_bill 244 non-null float64tip 244 non-null float64sex 244 non-null categorysmoker 244 non-null categoryday 244 non-null categorytime ... | # Câu 1: Vẽ violinplot cho cho cột total_bill
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWAAAAEHCAYAAACQkJyuAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nO3deXhV1b3/8fc6Y07meYCEhISQgIAoFFFEQcERB/ypONH7UymKA2ItDti... | # Câu 2: Vẽ swarmplot cho cột total_bill theo sex
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAX8AAAEGCAYAAACNaZVuAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nOydd3hUZfbHP3cmvfeekEYLLUDoTUARBOxgwV6wYVsbP7vrrq7urrq6soo... | # Câu 3: Vẽ boxplot cho cột total_bill
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWAAAAEHCAYAAACQkJyuAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAMPElEQVR4nO3df6zdd13H8dd77QxF0bluLKbDXfFixBCZySRE0CDptFPijyjB+IOaGIj... | # Câu 4: Tạo FacetGrid với 'time' và chỉ định thứ tự của các hàng bằng row_order, ánh xạ (map) của 'total_bill' lên lưới
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABHgAAAEYCAYAAAAnPkG+AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAVHUlEQVR4nO3df7Bmd10f8PcnuwsEQWMWTNuFdoXFUYoSdGUs2A44SV1aptBRhg5W1hm... | # Câu 5: Tạo Factor plot (phiên bản mới là catplot) chứa point plot của giá trị 'total_bill'
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWAAAALICAYAAABBxipSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+j8jraAAAgAElEQVR4nOzdeXxU9b3/8dcnK0nYIWyGVUAQZA1q3aqi1aoVrALaXqu3LreLVqtt1... | # Câu 6: Tạo PairGrid với một scatter plot "total_bill" và "tip"
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Nhấn vào đây để xem kết quả ! <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVIAAAFcCAYAAACa3zafAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nO3de5SU5Z0n8O+vi2ptCKZh0rLSSiCGxcSokPQIWbJzlAzBiUZ7vMQwmDV... | # Câu 7: Tạo Pairplot với một scatter plot "total_bill" và "tip", sử dụng palette color = 'day'
# Bạn nhận xét gì về biểu đồ vừa tạo
| _____no_output_____ | MIT | Chapter7_Exercise3_Tips.ipynb | packkkk/data-science-and-machine-learning-fundamentals |
Linear_Reg Author ~ Saurabh Kumar Date ~ 05-Dec-21 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
#simple_linera_regression
class Simple_linear_regression:
def __init__(self,learning_rate=1e-3,n_steps=1000):
self.learning_rate =learning_rate
self.n... | _____no_output_____ | Apache-2.0 | Linear_Regression_Scratch.ipynb | Saurabh2509/Linear_Regression_Scratch |
Collaboration and Competition---In this notebook, you will learn how to use the Unity ML-Agents environment for the third project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893) program. 1. Start the EnvironmentWe begin by importing the nece... | from unityagents import UnityEnvironment
import numpy as np
import random
import torch
from collections import deque
import matplotlib.pyplot as plt
%matplotlib inline
from ddpg_agent import Agent
plt.style.use('fivethirtyeight')
%load_ext autoreload
%autoreload 2
import warnings
warnings.filterwarnings('ignore') | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.- **Mac**: `"path/to/Tennis.app"`- **Windows** (x86): `"path/to/Tennis_Windows_x86/Tennis.exe"`- **Windows** (x86_64): `"path/to/Tennis_Wind... | # Under Linux
#env = UnityEnvironment(file_name='Tennis_Linux/Tennis.x86_64', seed=123)
# Under Mac
env = UnityEnvironment(file_name='Tennis.app', seed=123) | INFO:unityagents:
'Academy' started successfully!
Unity Academy name: Academy
Number of Brains: 1
Number of External Brains : 1
Lesson number : 0
Reset Parameters :
Unity brain name: TennisBrain
Number of Visual Observations (per agent): 0
Vector Observation space type... | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. | # get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name] | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
2. Examine the State and Action SpacesIn this environment, two agents control rackets to bounce a ball over a net. If an agent hits the ball over the net, it receives a reward of +0.1. If an agent lets a ball hit the ground or hits the ball out of bounds, it receives a reward of -0.01. Thus, the goal of each agent i... | # reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents
num_agents = len(env_info.agents)
print('Number of agents:', num_agents)
# size of each action
action_size = brain.vector_action_space_size
print('Size of each action:', action_size)
# examine the state space
states = env_... | Number of agents: 2
Size of each action: 2
There are 2 agents. Each observes a state with length: 24
The state for the first agent looks like: [ 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0.
0. 0. 0. 0. ... | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
3. Take Random Actions in the EnvironmentIn the next code cell, you will learn how to use the Python API to control the agents and receive feedback from the environment.Once this cell is executed, you will watch the agents' performance, if they select actions at random with each time step. A window should pop up that... | for i in range(1, 20): # play game for 5 episodes
env_info = env.reset(train_mode=False)[brain_name] # reset the environment
states = env_info.vector_observations # get the current state (for each agent)
scores = np.zeros(num_agents) ... | Score (max over agents) from episode 1: 0.0
Score (max over agents) from episode 2: 0.10000000149011612
Score (max over agents) from episode 3: 0.10000000149011612
Score (max over agents) from episode 4: 0.10000000149011612
Score (max over agents) from episode 5: 0.0
Score (max over agents) from episode 6: 0.0
Score (m... | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
When finished, you can close the environment. env.close() 4. It's Your Turn!Now it's your turn to train your own agent to solve the environment! When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following:```pythonenv_info = env.reset(train_mode=True)[... | # Utilities functions
def unity_step_wrap(actions):
"""Unity Environment action wrapper
Params
======
action (int): action to take
Return
======
OpenAI-like action outcome (tuple): bundled (next_state, reward, done)
"""
env_info = env.step(actions)[brain_name] ... | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
* **Solving the environment** | scores = ddpg(n_episodes=10000, min_noise=0.02, learn_every=5, name='solved')
_, _, scores_solved = load_checkpoint('saved-checkpoints/checkpoint-solved.pth')
figure = plot_scores(scores_solved) | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
* **Monitoring beyond solving scores in the long run** | scores = ddpg(n_episodes=10000, min_noise=0.01, learn_every=5, solved_score = 99, name='in-the-long-run')
_, _, scores_long_run = load_checkpoint('saved-checkpoints/checkpoint-in-the-long-run.pth')
figure = plot_scores(scores_long_run) | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
* **Watching solved environment agent in action** | # Reloading networks weights
actor_weights, critic_weights, scores_solved = load_checkpoint('saved-checkpoints/checkpoint-solved.pth')
# Instantiating the agent
agent = Agent(state_size=state_size, action_size=action_size, random_seed=2)
agent.actor_local.load_state_dict(actor_weights)
agent.critic_local.load_state_di... | _____no_output_____ | MIT | 15-p3-collab-compet/Tennis.ipynb | franckalbinet/my-drl-udacity-nanodegree |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. Testing different Hyperparameters and Benchmarking In this notebook, we will cover how to test different hyperparameters for a particular dataset and how to benchmark different parameters across a group of datasets using AzureML. ... | import os
import sys
from distutils.dir_util import copy_tree
import numpy as np
import scrapbook as sb
import uuid
import azureml.core
from azureml.core import Workspace, Experiment
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
import azureml... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
Ensure edits to libraries are loaded and plotting is shown in the notebook. | %reload_ext autoreload
%autoreload 2
%matplotlib inline | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
We now define some parameters which will be used in this notebook: | # Azure resources
subscription_id = "YOUR_SUBSCRIPTION_ID"
resource_group = "YOUR_RESOURCE_GROUP_NAME"
workspace_name = "YOUR_WORKSPACE_NAME"
workspace_region = "YOUR_WORKSPACE_REGION" #Possible values eastus, eastus2, etc.
# Choose a size for our cluster and the maximum number of nodes
VM_SIZE = "STANDARD_NC6" #S... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
1. Config AzureML workspaceBelow we setup (or load an existing) AzureML workspace, and get all its details as follows. Note that the resource group and workspace will get created if they do not yet exist. For more information regaring the AzureML workspace see also the [20_azure_workspace_setup.ipynb](../../classifica... | ws = get_or_create_workspace(
subscription_id, resource_group, workspace_name, workspace_region
)
# Print the workspace attributes
print(
"Workspace name: " + ws.name,
"Workspace region: " + ws.location,
"Subscription id: " + ws.subscription_id,
"Resource group: " + ws.resource_group,
sep="\n",... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
2. Create Remote TargetWe create a GPU cluster as our remote compute target. If a cluster with the same name already exists in our workspace, the script will load it instead. This [link](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targetscompute-targets-for-training) provides... | CLUSTER_NAME = "gpu-cluster"
try:
# Retrieve if a compute target with the same cluster name already exists
compute_target = ComputeTarget(workspace=ws, name=CLUSTER_NAME)
print("Found existing compute target.")
except ComputeTargetException:
# If it doesn't already exist, we create a new one with the ... | Creating a new compute target...
Creating
Succeeded
AmlCompute wait for completion finished
Minimum number of nodes requested have been provisioned
{'currentNodeCount': 0, 'targetNodeCount': 0, 'nodeStateCounts': {'preparingNodeCount': 0, 'runningNodeCount': 0, 'idleNodeCount': 0, 'unusableNodeCount': 0, 'leavingNodeCo... | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
The compute cluster and its status can be seen in the portal. For example in the screenshot below, its automatically resizing (eventually to 0 nodes) to adjust to the number of open runs: 3. Prepare dataIn this notebook, we'll use the Fridge Objects dataset, which is already stored in the correct format. We then uploa... | # Retrieving default datastore that got automatically created when we setup a workspace
ds = ws.get_default_datastore()
# We now upload the data to a unique sub-folder to avoid accidentially training/evaluating also including older images.
data_subfolder = str(uuid.uuid4())
ds.upload(
src_dir=DATA_PATH, target_pat... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
Here's where you can see the data in your portal: 4. Prepare training scriptNext step is to prepare scripts that AzureML Hyperdrive will use to train and evaluate models with selected hyperparameters. | # Create a folder for the training script and copy the utils_cv library into that folder
script_folder = os.path.join(os.getcwd(), "hyperdrive")
os.makedirs(script_folder, exist_ok=True)
_ = copy_tree(UTILS_DIR, os.path.join(script_folder, 'utils_cv'))
%%writefile $script_folder/train.py
# Use different matplotlib bac... | Overwriting C:\Users\pabuehle\Desktop\ComputerVision\scenarios\detection\hyperdrive/train.py
| MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
5. Setup and run Hyperdrive experiment 5.1 Create Experiment Experiment is the main entry point into experimenting with AzureML. To create new Experiment or get the existing one, we pass our experimentation name 'hyperparameter-tuning'. | exp = Experiment(workspace=ws, name="hyperparameter-tuning") | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
5.2. Define search spaceNow we define the search space of hyperparameters. To test discrete parameter values use 'choice()', and for uniform sampling use 'uniform()'. For more options, see [Hyperdrive parameter expressions](https://docs.microsoft.com/en-us/python/api/azureml-train-core/azureml.train.hyperdrive.paramet... | # Grid-search
param_sampling = GridParameterSampling(
{"--learning_rate": choice(LEARNING_RATES), "--max_size": choice(IM_MAX_SIZES)}
) | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
AzureML Estimator is the building block for training. An Estimator encapsulates the training code and parameters, the compute resources and runtime environment for a particular training scenario.We create one for our experimentation with the dependencies our model requires as follows: | script_params = {"--data-folder": ds.as_mount(), "--data-subfolder": data_subfolder}
est = Estimator(
source_directory=script_folder,
script_params=script_params,
compute_target=compute_target,
entry_script="train.py",
use_gpu=True,
pip_packages=["nvidia-ml-py3", "fastai"],
conda_packages=[... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
We now create a HyperDriveConfig object which includes information about parameter space sampling, termination policy, primary metric, estimator and the compute target to execute the experiment runs on. | hyperdrive_run_config = HyperDriveConfig(
estimator=est,
hyperparameter_sampling=param_sampling,
policy=None, # Do not use any early termination
primary_metric_name="accuracy",
primary_metric_goal=PrimaryMetricGoal.MAXIMIZE,
max_total_runs=None, # Set to none to run all possible grid parameter... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
5.3 Run ExperimentWe now run the parameter sweep and visualize the experiment progress using the `RunDetails` widget:Once completed, the accuracy for the different runs can be analyzed via the widget, for example below is a plot of the accuracy versus learning rate below (for two different image sizes) | hyperdrive_run = exp.submit(config=hyperdrive_run_config)
print(f"Url to hyperdrive run on the Azure portal: {hyperdrive_run.get_portal_url()}")
widgets.RunDetails(hyperdrive_run).show()
hyperdrive_run.wait_for_completion() | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
To load an existing Hyperdrive Run instead of start new one, we can use ```pythonhyperdrive_run = azureml.train.hyperdrive.HyperDriveRun(exp, , hyperdrive_run_config=hyperdrive_run_config)```We also can cancel the Run with ```python hyperdrive_run.cancel().```Once all the child-runs are finished, we can get the best ru... | # Get best run and print out metrics
best_run = hyperdrive_run.get_best_run_by_primary_metric()
best_run_metrics = best_run.get_metrics()
parameter_values = best_run.get_details()["runDefinition"]["arguments"]
best_parameters = dict(zip(parameter_values[::2], parameter_values[1::2]))
print(f"* Best Run Id:{best_run.id... | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
7. Clean upTo avoid unnecessary expenses, all resources which were created in this notebook need to get deleted once parameter search is concluded. To simplify this clean-up step, we recommended creating a new resource group to run this notebook. This resource group can then be deleted, e.g. using the Azure Portal, wh... | # Log some outputs using scrapbook which are used during testing to verify correct notebook execution
sb.glue("best_accuracy", best_run_metrics["accuracy"]) | _____no_output_____ | MIT | scenarios/detection/11_exploring_hyperparameters_on_azureml.ipynb | kant/ComputerVision |
4. Model TrainingThis notebook demonstrates how to train a Propensity Model using BigQuery ML. Requirements* Input features used for training needs to be stored as a BigQuery table. This can be done using [2. ML Data Preparation Notebook](2.ml_data_preparation.ipynb). Install and import required modules | # Uncomment to install required python modules
# !sh ../utils/setup.sh
# Add custom utils module to Python environment
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
from gps_building_blocks.cloud.utils import bigquery as bigquery_utils
from utils import model
from utils import helpers | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Set paramaters | configs = helpers.get_configs('config.yaml')
dest_configs = configs.destination
# GCP project ID
PROJECT_ID = dest_configs.project_id
# Name of the BigQuery dataset
DATASET_NAME = dest_configs.dataset_name
# To distinguish the separate runs of the training pipeline
RUN_ID = 'TRAIN_01'
# BigQuery table name containing... | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Next, let's configure modeling options. Model and features configuration Model options can be configured in detail based on BigQuery ML specificationslisted in [The CREATE MODEL statement](https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create).**NOTE**: Propensity modeling supports ... | # Read in Features table schema to select feature names for model training
sql = ("SELECT column_name "
f"FROM `{PROJECT_ID}.{DATASET_NAME}`.INFORMATION_SCHEMA.COLUMNS "
f"WHERE table_name='{FEATURES_DEV_TABLE}';")
print(sql)
features_schema = bq_utils.run_query(sql).to_dataframe()
# Columns to remove f... | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Train the modelFirst, we initialize `PropensityModel` with config parameters. | bq_utils = bigquery_utils.BigQueryUtils(project_id=PROJECT_ID)
propensity_model = model.PropensityModel(bq_utils=bq_utils,
params=params) | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Next cell triggers model training job in BigQuery which takes some time to finish depending on dataset size and model complexity. Set `verbose=True`, if you want to verify training query details. | propensity_model.train(verbose=False) | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Following cell allows you to see detailed information about the input features used to train a model. It provides following columns:- input — The name of the column in the input training data.- min — The sample minimum. This column is NULL for non-numeric inputs.- max — The sample maximum. This column is NULL for non-n... | propensity_model.get_feature_info() | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
Evaluate the modelThis section helps to do quick model evaluation to get following model metrics:* recall* accuracy* f1_score* log_loss* roc_aucTwo optional parameters can be specified for evaluation:* eval_table: BigQuery table containing evaluation dataset* threshold: Custom probability threshold to be used for... | # Model performance on the model development dataset on which the final
# model has been trained
EVAL_TABLE_NAME = FEATURES_DEV_TABLE
eval_params = {
'eval_table_path': f'{PROJECT_ID}.{DATASET_NAME}.{EVAL_TABLE_NAME}',
'threshold': 0.5
}
propensity_model.evaluate(eval_params, verbose=False)
# Model performance o... | _____no_output_____ | Apache-2.0 | packages/propensity/04.model_training.ipynb | google/compass |
We begin by loading in the vocabulary for the model of interest. This will let us check vocab size and to get the special ids for padding. | vocab = dict(torch.load("../../data/data.vocab.pt"))
src_padding = vocab["src"].stoi[onmt.inputters.PAD_WORD]
tgt_padding = vocab["tgt"].stoi[onmt.inputters.PAD_WORD] | _____no_output_____ | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
Next we specify the core model itself. Here we will build a small model with an encoder and an attention based input feeding decoder. Both models will be RNNs and the encoder will be bidirectional | emb_size = 10
rnn_size = 6
# Specify the core model.
encoder_embeddings = onmt.modules.Embeddings(emb_size, len(vocab["src"]),
word_padding_idx=src_padding)
encoder = onmt.encoders.RNNEncoder(hidden_size=rnn_size, num_layers=1,
rnn_type="L... | _____no_output_____ | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
Now we set up the optimizer. This could be a core torch optim class, or our wrapper which handles learning rate updates and gradient normalization automatically. | optim = onmt.utils.optimizers.Optimizer(method="sgd", lr=1, max_grad_norm=2)
optim.set_parameters(model.named_parameters()) | _____no_output_____ | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
Now we load the data from disk. Currently will need to call a function to load the fields into the data as well. | # Load some data
data = torch.load("../../data/data.train.1.pt")
valid_data = torch.load("../../data/data.valid.1.pt")
data.load_fields(vocab)
valid_data.load_fields(vocab)
data.examples = data.examples[:100] | _____no_output_____ | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
To iterate through the data itself we use a torchtext iterator class. We specify one for both the training and test data. | train_iter = onmt.inputters.OrderedIterator(
dataset=data, batch_size=10,
device=-1, ... | _____no_output_____ | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
Finally we train. | trainer = onmt.Trainer(model, loss, loss, optim)
def report_func(*args):
stats = args[-1]
stats.output(args[0], args[1], 10, 0)
return stats
for epoch in range(2):
trainer.train(epoch, report_func)
val_stats = trainer.validate()
print("Validation")
val_stats.output(epoch, 11, 10, 0)
t... | Epoch 0, 0/ 10; acc: 0.00; ppl: 1225.23; 1320 src tok/s; 1320 tgt tok/s; 1514090454 s elapsed
Epoch 0, 1/ 10; acc: 9.50; ppl: 996.33; 1188 src tok/s; 1194 tgt tok/s; 1514090454 s elapsed
Epoch 0, 2/ 10; acc: 16.51; ppl: 694.48; 1265 src tok/s; 1267 tgt tok/s; 1514090454 s elapsed
Epoch 0, ... | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
To use the model, we need to load up the translation functions | import onmt.translate
translator = onmt.translate.Translator(beam_size=10, fields=data.fields, model=model)
builder = onmt.translate.TranslationBuilder(data=valid_data, fields=data.fields)
valid_data.src_vocabs
for batch in valid_iter:
trans_batch = translator.translate_batch(batch=batch, data=valid_data)
tran... | PRED SCORE: -4.0690
SENT 0: ('The', 'competitors', 'have', 'other', 'advantages', ',', 'too', '.')
PRED 0: .
PRED SCORE: -4.2736
SENT 0: ('The', 'company', ''s', 'durability', 'goes', 'back', 'to', 'its', 'first', 'boss', ',', 'a', 'visionary', ',', 'Thomas', 'J.', 'Watson', 'Sr.')
PRED 0: .
PRED SCORE: -4.014... | MIT | docs/source/Library.ipynb | cmhcbb/Robustness_seq2seq |
决策树- 非参数学习算法- 天然解决多分类问题- 也可以解决回归问题- 非常好的可解释性 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn import datasets
iris = datasets.load_iris()
print(iris.DESCR)
X = iris.data[:, 2:] # 取后两个特征
y = iris.target
plt.scatter(X[y==0, 0], X[y==0, 1])
plt.scatter(X[y==1, 0], X[y==1, 1])
plt.scatter(X[y==2, 0],... | _____no_output_____ | MIT | ML-Base-MOOC/chapt-9 Decision Tree/01- Decision Tree and Entropy.ipynb | NovemberChopin/machine-learning |
1. scikit-learn 中的决策树 | from sklearn.tree import DecisionTreeClassifier
# entropy : 熵
dt_clf = DecisionTreeClassifier(max_depth=3, criterion="entropy")
dt_clf.fit(X, y)
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1] - axis[0])*100)).reshape(1, -1),
np.linspace... | /home/js/pyEnvs/tf_cpu/lib/python3.6/site-packages/ipykernel_launcher.py:15: UserWarning: The following kwargs were not used by contour: 'linewidth'
from ipykernel import kernelapp as app
| MIT | ML-Base-MOOC/chapt-9 Decision Tree/01- Decision Tree and Entropy.ipynb | NovemberChopin/machine-learning |
2. 如何构建决策树**问题**- 每个节点在那个维度做划分?- 某个维度在那个值上做划分?- 划分的标准就是,**划分后使得信息熵降低** **信息熵**- 熵在信息论中代表随机变量不确定的度量- 熵越大,数据的不确定性越高- 熵越小,数据的不确定性越低$$H = -\sum_{i=1}^kp_i\log{(p_i)}$$- 其中 $p_i$ 表示每一类信息在所有信息类别中占的比例- 对于二分类,香农公式为:$$H=-x\log(x)-(1-x)\log(1-x)$$ **信息熵函数** | def entropy(p):
return -p * np.log(p) - (1-p) * np.log(1-p)
x = np.linspace(0.01, 0.99)
plt.plot(x, entropy(x)) | _____no_output_____ | MIT | ML-Base-MOOC/chapt-9 Decision Tree/01- Decision Tree and Entropy.ipynb | NovemberChopin/machine-learning |
- 可以看出,当 x 越接近0.5,熵越高 3. 模拟使用信息熵进行划分 | # 基于维度 d 的 value 值进行划分
def split(X, y, d, value):
index_a = (X[:, d] <= value)
index_b = (X[:, d] > value)
return X[index_a], X[index_b], y[index_a], y[index_b]
from collections import Counter
from math import log
# 计算每一类样本点的熵的和
def entropy(y):
counter = Counter(y)
res = 0.0
for num in counter.v... | best_entropy = 0.6931471805599453
best_d 0
best_v 2.45
| MIT | ML-Base-MOOC/chapt-9 Decision Tree/01- Decision Tree and Entropy.ipynb | NovemberChopin/machine-learning |
**即在第 0 个维度的 2.45 位置进行划分,可以得到最低的熵,值为 0.693** | X1_l, X1_r, y1_l, y1_r = split(X, y, best_d, best_v)
entropy(y1_r)
entropy(y1_l) # 从上图可以看出,粉红色部分只有一类,故熵为 0
best_entropy2, best_d2, best_v2 = try_split(X1_r, y1_r)
print("best_entropy = ", best_entropy2)
print("best_d", best_d2)
print("best_v", best_v2)
X2_l, X2_r, y2_l, y2_r = split(X1_r, y1_r, best_d2, best_v2)
entro... | _____no_output_____ | MIT | ML-Base-MOOC/chapt-9 Decision Tree/01- Decision Tree and Entropy.ipynb | NovemberChopin/machine-learning |
We compute here the number of labels concurrent at t. | df_price = fml.DataHandler().get_time_series_data("SPY")
price = fml.Price(df_price["Adj Close"], freq="B")
cross_time = price.bounds_cross_time(window=10)
cross_time.index = range(len(cross_time))
cross_time.head()
cross_time_int = cross_time.min(axis=1).to_frame("cross")
cross_time_int["cnt"] = 0
cross_time_int.head(... | _____no_output_____ | MIT | notebooks/num_concurrent_event.ipynb | aliciawyy/financial_machine_learning |
1. Extract your dataset and split into train_x, train_y, test_x and test_y.
2. Execute the following cells --- Hybrid Social Group Optimization --- | N = 5 # Number of persons in population
D = len(train_x.columns) # Number of features in dataset
g = 10 # Number of generations
c = 0.6 # Self Introspection factor
r0 = 1
r1 = 0.4
r2 = 0.6
print(r1, r2) | 0.4 0.6
time: 3.13 ms (started: 2021-01-22 18:19:07 +00:00)
| Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
**Population Initialization** | population = np.random.choice([0,1,2,3,4,5,6,7,8,9], (N,D), p=[0.16, 0.16, 0.16, 0.16, 0.16, 0.04, 0.04, 0.04, 0.04, 0.04]) #Determines no. of features selected by probablity
population = population.astype(float)
print(population.shape)
population
fitness = np.zeros(N)
test_x.shape
def fitter_trait(X_old, X_new):
if ... | time: 2.58 ms (started: 2021-01-22 18:19:07 +00:00)
| Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
**Fitness Function** | global classifier
classifier = Svc #Change classifier here
select = train_x.columns
selectno = len(train_x.columns)
classifier.fit(train_x, train_y)
select_acc = classifier.score(test_x, test_y)
def fitness_function(pop): #Fitness Function
for i in range(N):
new_train_x = train_x
new_test_x = test_x... | time: 785 µs (started: 2021-01-22 18:19:13 +00:00)
| Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
**Gbest : Fittest person in population** | ###Determining GBest
gbest = 0
gbest_i = 0
def find_gbest():
gbest = max(fitness)#This can be any function
gbest_i = fitness.argmax()
print("Best fitness value for the generation = "+str(gbest) + " Person " + str(gbest_i+1)+"\n")
find_gbest()
#we chose maximum fitness value to be better for simplicity
def cal_fi... | (1, 10000)
| Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
---**Mutation Phase** | def mutate():
gworst_i = fitness.argmin()
gworst = min(fitness)
mut = np.random.randint(0,2,size=(1,D))[0]
print("Mutating the Generation's Worst....Person "+ str(gworst_i+1))
for i in range(D):
if mut[i] > 0:
mut[i] = population[gbest_i][i]
else:
mut[i] = population[gworst_i][i]
if cal_... | time: 1.79 ms (started: 2021-01-22 18:19:15 +00:00)
| Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
---**Improving Phase** | ## Improving Phase
# i = 1
def improve():
print("Improving.......")
for i in range(N):
Xnew = population[i]
print('Persona '+ str(i+1))
for j in range(D):
Xnew[j] = c * population[i][j] + r0 * (population[gbest_i][j] - population[i][j])
try:
if cal_fitness(Xnew) > fitness[i]:
pop... | _____no_output_____ | Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
---**Acquiring Phase** | ## Acquiring Phase
def acquire():
random_person = np.random.randint(low=0, high=N)
for i in range(N):
if random_person == i:
random_person = np.random.randint(low=0, high=N)
i = i - 1
continue
X_new = population[i]
if fitness[random_person] > fitness[i]:
for j in range(D):
... | _____no_output_____ | Apache-2.0 | Hybrid_SGO.ipynb | Enixes/Hybrid-Social-Group-Optimization-algorithm |
Boolean Mask Arrays | import numpy as np
my_vector = np.array([-17, -4, 0, 2, 21, 37, 105])
my_vector | _____no_output_____ | MIT | numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 3/03_02/Starting/.ipynb_checkpoints/Boolean Mask Arrays-checkpoint.ipynb | saint1729/in-learning |
ClusterFinder Reference genomes reconstructionThis notebook validates the 10 genomes we obtained from NCBI based on the ClusterFinder supplementary table. We check that the gene locations from the supplementary table match locations in the GenBank files. | from Bio import SeqIO
from Bio.SeqFeature import FeatureLocation
import pandas as pd
from Bio import Entrez
import seaborn as sns
def get_features_of_type(sequence, feature_type):
return [feature for feature in sequence.features if feature.type == feature_type]
def get_reference_gene_location(gene_csv_row):
st... | _____no_output_____ | MIT | notebooks/ClusterFinderLabelledContigCheck.ipynb | prihoda/bgc-pipeline-1 |
Loading reference cluster gene locations | reference_genes = pd.read_csv('../data/clusterfinder/labelled/CF_labelled_genes_orig.csv', sep=';')
reference_genes.head() | _____no_output_____ | MIT | notebooks/ClusterFinderLabelledContigCheck.ipynb | prihoda/bgc-pipeline-1 |
Genes with no sequence | no_sequence_genes = reference_genes[reference_genes['NCBI ID'] == '?']
no_sequence_counts = no_sequence_genes.groupby('Genome ID')['gene locus'].count()
print('{} genes don\'t have a sequence!'.format(len(no_sequence_genes)))
pd.DataFrame({'missing genes':no_sequence_counts})
reference_ids = reference_genes[reference_g... | _____no_output_____ | MIT | notebooks/ClusterFinderLabelledContigCheck.ipynb | prihoda/bgc-pipeline-1 |
Validating that reference genes are found in our sequences | def validate_genome(record, record_reference_genes):
print('Validating {}'.format(record.id))
record_genes = get_features_of_type(record, 'gene')
record_cds = get_features_of_type(record, 'CDS')
validation = []
record_length = len(record.seq)
min_location = record_length
max_location = -1
... | _____no_output_____ | MIT | notebooks/ClusterFinderLabelledContigCheck.ipynb | prihoda/bgc-pipeline-1 |
Cluster genes | genes = pd.read_csv('../data/clusterfinder/labelled/CF_labelled_genes.csv', sep=';')
genes.head()
cluster_counts = genes.groupby('contig_id')['cluster_id'].nunique()
cluster_counts.sort_values().plot.barh()
gene_counts = genes.groupby('cluster_id')['locus_tag'].count()
gene_counts.hist(bins=50) | _____no_output_____ | MIT | notebooks/ClusterFinderLabelledContigCheck.ipynb | prihoda/bgc-pipeline-1 |
Realization of Recursive Filters*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* Cascaded StructuresThe realization of recursive f... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.markers import MarkerStyle
from matplotlib.patches import Circle
import scipy.signal as sig
N = 9 # order of recursive filter
def zplane(z, p, title='Poles and Zeros'):
"Plots zero and pole locations in the complex z-plane"
... | Coefficients of the recursive part
['1.00', '-5.39', '13.38', '-19.96', '19.62', '-13.14', '5.97', '-1.78', '0.31', '-0.02']
Coefficients of the recursive part of the individual SOS
Section a1 a2
0 -0.50953 0.00000
1 -1.04232 0.28838
2 -1.11568 0.37905
3 -1.25052 0.54572
4 -1.46818 0... | MIT | recursive_filters/cascaded_structures.ipynb | davidjustin1974/digital-signal-processing-lecture |
Utilizing daal4py in Data Science WorkflowsThe notebook below has been made to demonstrate daal4py in a data science context. It utilizes a Cycling Dataset for pyworkout-toolkit, and attempts to create a linear regression model from the 5 features collected for telemetry to predict the user's Power output in the abse... | import pandas as pd
import matplotlib.pyplot as plt
import glob
import sys
%matplotlib inline
sys.version | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
This example will be exploring workout data pulled from Strava, processed into a CSV for Pandas and daal4py usage. Below, we utilize pandas to read in the CSV file, and look at the head of dataframe with .head() | workout_data_dd= pd.read_csv('data/batch/cycling_dataset.csv', index_col=0)
workout_data_dd.head() | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
The data above has several key features that would be of great use here. - Altitude can affect performance, so it might be a useful feature. - Cadence is the revolutions per minute of the crank, and may have possible influence. - Heart Rate is a measure of the body's workout strain, and would have a high possibly of... | workout_data_dd.plot.scatter('cadence','power')
plt.show()
workout_data_dd.plot.scatter('hr','power')
plt.show()
workout_data_dd.plot.scatter('cadence','speed')
plt.show()
workout_data_dd.plot.scatter('speed','power')
plt.show()
workout_data_dd.plot.scatter('altitude','power')
plt.show()
workout_data_dd.plot.scatter('d... | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Using daal4py for Machine Learning tasksIn the sections below, we will be using daal4py directly. After importing the model, we will arrange it in a separate independent and dependent dataframes, then use the daal4py's training and prediction classes to generate a workable model. | import daal4py as d4p | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
It is now the time to split the dataset into train and test sets. This is demonstrated below. | print(workout_data_dd.shape)
train_set = workout_data_dd[0:3000]
test_set = workout_data_dd[3000:]
print(train_set.shape, test_set.shape)
# Reduce the dataset, create X. We drop the target, and other non-essential features.
reduced_dataset = train_set.drop(['time','power','latitude','longitude'], axis=1)
# Get the tar... | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
X is 5 features by 3k rows, Y is 3k rows by 1 column | print(reduced_dataset.values.shape, target.shape) | (3000, 5) (3000, 1)
| Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Training the model Create the Linear Regression Model, and train the model with the data. We utilize daal4py's linear_regression_training class to create the model, then call .compute() with the independent and dependent data as the parameters. | d4p_lm = d4p.linear_regression_training(interceptFlag=True)
lm_trained = d4p_lm.compute(reduced_dataset.values, target)
print("Model has this number of features: ", lm_trained.model.NumberOfFeatures) | Model has this number of features: 5
| Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Prediction (inference) with the trained model Now that the model is trained, we can test it with the test part of the dataset. We drop the same features to match that of the trained model, and put it into daal4py's linear_regression_prediction class. | subset = test_set.drop(['time','power','latitude','longitude'], axis=1) | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Now we can create the Prediction object and use the reduced dataset for prediction. The class's arguments use the independent data and the trained model from above as the parameters. | lm_predictor_component = d4p.linear_regression_prediction()
result = lm_predictor_component.compute(subset.values, lm_trained.model)
plt.plot(result.prediction[0:300])
plt.plot(test_set.power.values[0:300])
plt.show() | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
The graph above shows the Orange (predicted) result over the Blue (original data). This data is notoriously sparse in features leading to a difficult to predict target! Model propertiesAnother aspect of the model is the trained model's properties, which are explored below. | print("Betas:",lm_trained.model.Beta)
print("Number of betas:", lm_trained.model.NumberOfBetas)
print("Number of Features:", lm_trained.model.NumberOfFeatures) | Betas: [[ 1.51003501e+01 -1.25075548e-01 1.32249115e+00 1.64363922e-03
8.53155955e-01 -1.09595022e+01]]
Number of betas: 6
Number of Features: 5
| Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Additional metricsWe can generate metrics on the independent data with daal4py's low_order_moments() class. | metrics_processor = d4p.low_order_moments()
data = metrics_processor.compute(reduced_dataset.values)
data.standardDeviation | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
Migrating the trained model for inference on external systemsOccasionally one may need to migrate the trained model to another system for inference only--this use case allows the training on a much more powerful machine with a larger dataset, and placing the trained model for inference-only on a smaller machine. | import pickle
with open('trained_model2.pickle', 'wb') as model_pi:
pickle.dump(lm_trained.model, model_pi)
model_pi.close | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
The trained model file above can be moved to an inference-only or embedded system. This is useful if the training is extreamly heavy or computed-limited. | with open('trained_model2.pickle', 'rb') as model_import:
lm_import = pickle.load(model_import) | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
The imported model from file is now usable again. We can check the betas from the model to ensure that the trained model is present. | lm_import.Beta | _____no_output_____ | Apache-2.0 | examples/daal4py_data_science.ipynb | maria-Petrova/daal4py |
ME 3264 - Applied Measurements Laboratory===========================================Lab 5 - Linear Variable Differential Transformer(LVDT)===================================================== ObjectiveThe objectives of this laboratory are :1. Gain familiarity with the physical operating principle of Linear Variable Dif... | from scipy.optimize import curve_fit
def func(x,a,b):
'''fits the linear equation y = a + bx
This equation can be replaced by polynomial or exponential
as per the fitting goals of the problem'''
return (a + b*x)
x = [5,6,7,4,3,2,1] # mm
y = [4.829,6.690,8.333,3.686,2.024,0.145,-1.738] # Volt
k,... | Caliberation equation for LVDT is y = -3.163 +1.647x
Caliberation coefficent a =-3.163 +/- 0.185
Caliberation coefficent b = 1.647 +/- 0.041
| BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Note - In the curvefit,`k,pcov=curve_fit(func, x, y)`* `k` - Optimal values for the parameters so that the sum of the squared residuals of (f(x,k) - y) is minimized.* `pcov` - The estimated covariance of k. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the par... | ## # enter your work here - Uncomment the following lines of code and make necessary changes
# n = len(x)
# # sum of squares
# x_mean = np.mean(x)
# y_mean =
# ss_xx = np.sum((x-x_mean)**2)
# ss_yy =
# ss_xy = np.sum((y-y_mean)*(x-x_mean))
# # linear regression coefficients
# b = ss_xy/ss_xx
# a = y_mean - b*x_me... | Nice work!
| BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Part 2 - Calibrate Piezoelectric with LVDT outputIn part 2, you compare the amplitude of input voltage for the piezoelectric motion to the amplitude of LVDT voltage output. When the output voltage is larger, the piezoelectric is moving further. | from IPython.display import YouTubeVideo
YouTubeVideo('NwE8B9IHvyo') | _____no_output_____ | BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Problem 3 - Calibrate PiezoelectricFollowing table consists of amplitude of input voltage for the piezoelectric motion, and LVDT voltage output, recorded by DAQ in an experiment. Obtain the caliberation curve using linear regression. You can use `curve_fit` as expalined in Part 1. |Input, Vpp | Output Vpp ||--- ... | ## enter your work here | _____no_output_____ | BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Part 3 - Explore frequency-response between Piezoelectric and LVDTIn part 3, you vary the frequency input to the piezoelectric and measure the frequency output measured by the LVDT. You are constrained by the Nyquist frequency in these measurements. If you collect data at 500 Hz, then the largest frequency you can rel... | N=20
t_collect=10 # time to collect data
t=np.linspace(0,t_collect,1000)
y=np.cos(2*pi*t)
tsample=np.linspace(0,10,N+1)
ysample=np.cos(2*pi*tsample)
plt.figure(20)
plt.plot(t,y,label='signal')
plt.plot(tsample,ysample,'o-',label='measure')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('time (... | _____no_output_____ | BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.