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 |
|---|---|---|---|---|---|
Time-Series Analysis | from statsmodels.tsa.arima_process import arma_generate_sample
# Gerando dados
np.random.seed(12345)
arparams = np.array([.75, -.25])
maparams = np.array([.65, .35])
# Parâmetros
arparams = np.r_[1, -arparams]
maparam = np.r_[1, maparams]
nobs = 250
y = arma_generate_sample(arparams, maparams, nobs)
dates = sm.tsa.date... | ARMA Model Results
==============================================================================
Dep. Variable: y No. Observations: 250
Model: ARMA(2, 2) Log Likelihood -245.887
Meth... | MIT | Data Science Academy/Cap08/Notebooks/DSA-Python-Cap08-07-StatsModels.ipynb | srgbastos/Artificial-Intelligence |
Bring Your Own Algorithm to SageMaker Architecture of this notebook 1. Traininga. [Bring Your Own Container](byoc)b. [Training locally](local_train)c. [Trigger remote training job](remote_train)d. [Test locally](local_test) 2. Deploy EndPoint[Deploy model to SageMaker Endpoint](deploy_endpoint) 3. Build Lambda Functi... | import boto3
session = boto3.session.Session()
region = session.region_name
client = boto3.client("sts")
account_id = client.get_caller_identity()["Account"]
algorithm_name = "vgg16-audio" | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
3 elements to build bring your own container * `build_and_push.sh` is the script communicating with ECR * `Dockerfile` defines the training and serving environment * `code/train` and `code/serve` defines entry point of our container | !./build_and_push.sh
!cat Dockerfile
!cat build_and_push.sh | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
* construct image uri by account_id, region and algorithm_name | image_uri=f"{account_id}.dkr.ecr.{region}.amazonaws.com/{algorithm_name}"
image_uri | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
* prepare necessary variables/object for training | import sagemaker
session = sagemaker.session.Session()
bucket = session.default_bucket()
from sagemaker import get_execution_role
role = get_execution_role()
print(role)
s3_path = f"s3://{bucket}/data/competition"
s3_path | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Dataset Description - Dataset used in this workshop can be obtained from [Dog Bark Sound AI competition](https://tbrain.trendmicro.com.tw/Competitions/Details/15) hold by the world leading pet camera brand [Tomofun](https://en.wikipedia.org/wiki/Tomofun). The url below will be invalid after workshop. | # s3://tomofun-audio-classification-yianc
# data/data.zip
!wget https://www.dropbox.com/s/gvcswtrmdnhyiwo/Final_Training_Dataset.zip?dl=1
!unzip -o Final_Training_Dataset.zip?dl=1
!mv Final_Training_Dataset/train.zip ./
!unzip -o train.zip
!aws s3 cp --recursive ./train/ $s3_path | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Train model in a docker container with terminal interface * start container in interactive mode```IMAGE_ID=$(sudo docker images --filter=reference=vgg16-audio --format "{{.ID}}")nvidia-docker run -it -v $PWD:/opt/ml --entrypoint '' $IMAGE_ID bash ```* train model based on README.md```python train.py --csv_path=/opt/m... | from datetime import datetime
now = datetime.now()
timestamp = datetime.timestamp(now)
job_name = "audio-{}".format(str(int(timestamp)))
job_name | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Start SageMaker Training Job* sagemaker training jobs can run either locally or remotely | mode = 'remote'
if mode == 'local':
csess = sagemaker.local.LocalSession()
else:
csess = session
print(csess)
estimator = sagemaker.estimator.Estimator(
role=role,
image_uri=image_uri,
instance_count=1,
# insta... | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Test Model Locally * start container in interactive mode```IMAGE_ID=$(sudo docker images --filter=reference=vgg16-audio --format "{{.ID}}")nvidia-docker run -it -v $PWD:/opt/ml --entrypoint '' $IMAGE_ID bash ```* test model based on README.md```python test.py --test_csv /opt/ml/input/data/competition/meta_train.csv --... | predictor = estimator.deploy(instance_type='ml.p2.xlarge', initial_instance_count=1, serializer=sagemaker.serializers.IdentitySerializer())
# predictor = estimator.deploy(instance_type='local_gpu', initial_instance_count=1, serializer=sagemaker.serializers.IdentitySerializer())
endpoint_name = predictor.endpoint_name | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
You can deploy by using model file directly The Source code is as below. we can use model locally trained to deploy a sagemaker endpoint get example model file from s3 ```source_model_data_url = 'https://tinyurl.com/yh7tw3hj'!wget -O model.tar.gz $source_model_data_urlMODEL_PATH = f's3://{bucket}/model'model_data_s... | import json
file_name = "./input/data/competition/train/train_00002.wav"
with open(file_name, 'rb') as image:
f = image.read()
b = bytearray(f)
results = predictor.predict(b)
detections = json.loads(results)
print(detections) | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Create Lambda Function | import time
iam = boto3.client("iam")
role_name = "AmazonSageMaker-LambdaExecutionRole"
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": ["sagemaker.amazonaws.com", "lambda.amazonaws.com"]
}... | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Test Material ```{ "content": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBYWFRgWFRUZGRgYGBgYGBoYGBoYGBgYGhgZGRgYGBgcIS4lHB4rIRgYJjgmKy8xNTU1GiQ7QDs0Py40NTEBDAwMEA8QHxISHjQrJCQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NP/AABEIAMMBAgMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAEAAIDBQYBB//EADkQAAEDAgQEBAM... | !aws lambda add-permission \
--function-name invoke_endpoint \
--action lambda:InvokeFunction \
--statement-id apigateway \
--principal apigateway.amazonaws.com
!sed "s/<account_id>/$account_id/g" latestswagger2-template.json > latestswagger2-tmp.json
!sed "s/<region>/$region/g" latestswagger2-tm... | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Manually Setup API-Gateway in Console Create Restful API Create resource and methods * click the drop down manual and name your resource * focus on the resource just created, click the drop down manual and select create method, then select backend lambda function Configurations for passing the binary content to ... | api_endpoint = "https://{}.execute-api.{}.amazonaws.com/dev/classify".format(api_id, region)
!curl -X POST -H 'content-type: application/octet-stream' --data-binary @./input/data/competition/train/train_00002.wav $api_endpoint
%store endpoint_name
%store lambda_role_arn
%store model_s3_path | _____no_output_____ | MIT-0 | 01-byoc/audio.ipynb | asfhiolNick/incremental-training-mlops |
Hybrid Recommendations with the Movie Lens Dataset __Note:__ It is recommended that you complete the companion [__als_bqml.ipynb__](../solutions/als_bqml.ipynb) notebook before continuing with this __als_bqml_hybrid.ipynb__ notebook. If you already have the movielens dataset and trained model you can skip the "Import... | import os
import tensorflow as tf
PROJECT = "your-project-id-here" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["TFVERSION"] = '2.5' | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Import the dataset and trained modelIn the previous notebook, you imported 20 million movie recommendations and trained an ALS model with BigQuery MLTo save you the steps of having to do so again (if this is a new environment) you can run the below commands to copy over the clean data and trained model. First create t... | !bq mk movielens | BigQuery error in mk operation: Dataset 'qwiklabs-gcp-00-20dab82189fb:movielens'
already exists.
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Next, copy over the trained recommendation model. Note that if you're project is in the EU you will need to change the location from US to EU below. Note that as of the time of writing you cannot copy models across regions with `bq cp`. | %%bash
bq --location=US cp \
cloud-training-demos:movielens.recommender_16 \
movielens.recommender_16
bq --location=US cp \
cloud-training-demos:movielens.recommender_hybrid \
movielens.recommender_hybrid | Table 'cloud-training-demos:movielens.recommender_16' successfully copied to 'qwiklabs-gcp-00-20dab82189fb:movielens.recommender_16'
Table 'cloud-training-demos:movielens.recommender_hybrid' successfully copied to 'qwiklabs-gcp-00-20dab82189fb:movielens.recommender_hybrid'
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Next, ensure the model still works by invoking predictions for movie recommendations: | %%bigquery --project $PROJECT
SELECT * FROM
ML.PREDICT(MODEL `movielens.recommender_16`, (
SELECT
movieId, title, 903 AS userId
FROM movielens.movies, UNNEST(genres) g
WHERE g = 'Comedy'
))
ORDER BY predicted_rating DESC
LIMIT 5 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Incorporating user and movie information The matrix factorization approach does not use any information about users or movies beyond what is available from the ratings matrix. However, we will often have user information (such as the city they live, their annual income, their annual expenditure, etc.) and we will almo... | %%bigquery --project $PROJECT
SELECT
processed_input,
feature,
TO_JSON_STRING(factor_weights) AS factor_weights,
intercept
FROM ML.WEIGHTS(MODEL `movielens.recommender_16`)
WHERE
(processed_input = 'movieId' AND feature = '96481')
OR (processed_input = 'userId' AND feature = '54192') | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Multiplying these weights and adding the intercept is how we get the predicted rating for this combination of movieId and userId in the matrix factorization approach.These weights also serve as a low-dimensional representation of the movie and user behavior. We can create a regression model to predict the rating given ... | %%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.users AS
SELECT
userId,
RAND() * COUNT(rating) AS loyalty,
CONCAT(SUBSTR(CAST(userId AS STRING), 0, 2)) AS postcode
FROM
movielens.ratings
GROUP BY userId | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Input features about users can be obtained by joining the user table with the ML weights and selecting all the user information and the user factors from the weights array. | %%bigquery --project $PROJECT
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights)) AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'userId' AND feature = CAST(u.userId AS STRING)
)
SELECT * FROM userFe... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Similarly, we can get product features for the movies data, except that we have to decide how to handle the genre since a movie could have more than one genre. If we decide to create a separate training row for each genre, then we can construct the product features using. | %%bigquery --project $PROJECT
WITH productFeatures AS (
SELECT
p.* EXCEPT(genres),
g, (SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS product_factors
FROM movielens.movies p, UNNEST(genres) g
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'movieId' AND ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Combining these two WITH clauses and pulling in the rating corresponding the movieId-userId combination (if it exists in the ratings table), we can create the training dataset.**TODO 1**: Combine the above two queries to get the user factors and product factor for each rating. **NOTE**: The below cell will take approxi... | %%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.hybrid_dataset AS
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
One of the rows of this table looks like this: | %%bigquery --project $PROJECT
SELECT *
FROM movielens.hybrid_dataset
LIMIT 1 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Essentially, we have a couple of attributes about the movie, the product factors array corresponding to the movie, a couple of attributes about the user, and the user factors array corresponding to the user. These form the inputs to our “hybrid” recommendations model that builds off the matrix factorization model and a... | %%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_users(u ARRAY<FLOAT64>)
RETURNS
STRUCT<
u1 FLOAT64,
u2 FLOAT64,
u3 FLOAT64,
u4 FLOAT64,
u5 FLOAT64,
u6 FLOAT64,
u7 FLOAT64,
u8 FLOAT64,
u9 FLOAT64,
u10 ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
which gives: | %%bigquery --project $PROJECT
SELECT movielens.arr_to_input_16_users(u).*
FROM (SELECT
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.] AS u) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
We can create a similar function named movielens.arr_to_input_16_products to convert the product factor array into named columns.**TODO 2**: Create a function that returns named columns from a size 16 product factor array. | %%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_products(p ARRAY<FLOAT64>)
RETURNS
STRUCT<
p1 FLOAT64,
p2 FLOAT64,
p3 FLOAT64,
p4 FLOAT64,
p5 FLOAT64,
p6 FLOAT64,
p7 FLOAT64,
p8 FLOAT64,
p9 FLOAT64,
p... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Then, we can tie together metadata about users and products with the user factors and product factors obtained from the matrix factorization approach to create a regression model to predict the rating: **NOTE**: The below cell will take approximately 25~30 minutes for the completion. | %%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender_hybrid
OPTIONS(model_type='linear_reg', input_label_cols=['rating'])
AS
SELECT
* EXCEPT(user_factors, product_factors),
movielens.arr_to_input_16_users(user_factors).*,
movielens.arr_to_input_16_products(product_factors).*
FROM
mo... | Executing query with job ID: 3ccc5208-b63e-479e-980f-2e472e0d65ba
Query executing: 1327.21s | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml_hybrid.ipynb | Glairly/introduction_to_tensorflow |
Outliers | # day_1 (should be 0-3)
fig = plt.figure(figsize=(20, 5))
plt.subplot(1, 3, 1)
ax = df_num_data['day_1'].hist(bins=60)
ax.set_ylabel("Ionograms")
ax.set_xlabel("day_1")
# day_1 outliers above 10
plt.subplot(1, 3, 2)
ax = df_num_data[df_num_data['day_1']>=10]['day_1'].hist(bins=50)
ax.set_xlabel("day_1")
# day_1 belo... | 14487
421789
% error: 9.830987481187577
| MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Output data | df_num_data.to_csv("data/all_num_data.csv")
df_dot_data.to_csv("data/all_dot_data.csv")
df_loss.to_csv("data/all_loss.csv")
df_outlier.to_csv("data/all_outlier.csv")
df_num_data = pd.read_csv("data/all_num_data.csv") | _____no_output_____ | MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Combine columns | df_num_data['day'] = df_num_data.apply(lambda x: int(str(x['day_1']) + str(x['day_2']) + str(x['day_3'])), axis=1)
df_num_data['hour'] = df_num_data.apply(lambda x: int(str(x['hour_1']) + str(x['hour_2'])), axis=1)
df_num_data['minute'] = df_num_data.apply(lambda x: int(str(x['minute_1']) + str(x['minute_2'])), axis=1)... | Rows in unfiltered df: 467776
Errors in 'year': 258
Errors in 'day': 32383
Errors in 'hour': 8860
Errors in 'minute': 4337
Errors in 'second': 8107
Errors in 'station_number': 194
Errors in 'satellite_number': 6332
Rows in filtered df: 407305
Total error rate: 12.92734129155835
| MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Convert to datetime object | filtered_df2 = filtered_df.copy()
filtered_df['timestamp'] = filtered_df.apply(lambda x: datetime.datetime(year=1962, month=1, day=1) + \
relativedelta(years=x['year'], days=x['day']-1, hours=x['hour'], minutes=x['minute'], seconds=x['second']), axis=1)
filtered_df2['timestamp'] = filtered_df2.apply... | _____no_output_____ | MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Fix file naming | #def fix_file_name(file_name):
# dir_0 = []
# dir_1 = []
# dir_2 = []
# dir_3 = []
# file_array = filtered_df.iloc[i]['file_name'].replace('\\', '/').split('/')
# file_array[-3:]
df_final = filtered_df.copy()
df_final['file_name'] = filtered_df.apply(lambda x: '/'.join(x['file_name'].replace('\\', '/').split(... | _____no_output_____ | MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Drop unnecessary columns | df_final.columns
df_final = df_final.drop(columns=['Unnamed: 0', 'year', 'day_1', 'day_2', 'day_3', 'hour_1','hour_2', 'minute_1', 'minute_2',\
'second_1', 'second_2','station_number_1', 'station_number_2', 'day', 'hour', 'minute','second']) | _____no_output_____ | MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Export final dateframe | len(df_final.index)
df_final.to_csv("data/final_alouette_data.csv") | _____no_output_____ | MIT | data_cleaning/notebooks/data_cleaning.ipynb | CamRoy008/AlouetteApp |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. Installation and configurationThis notebook configures the notebooks in this tutorial to connect to an Azure Machine Learning (AML) Workspace. You can use an existing workspace or create a new one. | import azureml.core
from azureml.core import Workspace
from azureml.core.authentication import ServicePrincipalAuthentication, AzureCliAuthentication, \
InteractiveLoginAuthentication
from azureml.exceptions import AuthenticationException
from dotenv import set_key, get_key, find_dotenv
from pathlib import Path | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Prerequisites If you have already completed the prerequisites and selected the correct Kernel for this notebook, the AML Python SDK is already installed. Let's check the AML SDK version. | print("AML SDK Version:", azureml.core.VERSION) | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Set up your Azure Machine Learning workspace To create or access an Azure ML Workspace, you will need the following information:* Your subscription id* A resource group name* A name for your workspace* A region for your workspace**Note**: As with other Azure services, there are limits on certain resources like cluster... | # Azure resources
subscription_id = ""
resource_group = ""
workspace_name = ""
workspace_region = ""
tenant_id = "YOUR_TENANT_ID" # Optional for service principal authentication
username = "YOUR_SERVICE_PRINCIPAL_APPLICATION_ID" # Optional for service principal authentication
password = "YOUR_SERVICE_PRINCIPAL_PAS... | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Create and initialize a dotenv file for storing parameters used in multiple notebooks. | env_path = find_dotenv()
if env_path == "":
Path(".env").touch()
env_path = find_dotenv()
set_key(env_path, "subscription_id", subscription_id) # Replace YOUR_AZURE_SUBSCRIPTION
set_key(env_path, "resource_group", resource_group)
set_key(env_path, "workspace_name", workspace_name)
set_key(env_path, "workspace_r... | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Create the workspaceThis cell will create an AML workspace for you in a subscription, provided you have the correct permissions.This will fail when:1. You do not have permission to create a workspace in the resource group2. You do not have permission to create a resource group if it's non-existing.2. You are not a sub... | def get_auth(env_path):
if get_key(env_path, 'password') != "YOUR_SERVICE_PRINCIPAL_PASSWORD":
aml_sp_password = get_key(env_path, 'password')
aml_sp_tennant_id = get_key(env_path, 'tenant_id')
aml_sp_username = get_key(env_path, 'username')
auth = ServicePrincipalAuthentication(
... | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Let's check the details of the workspace. | ws.get_details() | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
Let's write the workspace configuration for the rest of the notebooks to connect to the workspace. | ws.write_config() | _____no_output_____ | MIT | 00_AMLConfiguration.ipynb | Bhaskers-Blu-Org2/az-ml-batch-score |
The ARMI Material LibraryWhile *nuclides* are the microscopic building blocks of nature, their collection into *materials* is what we interact with at the engineering scale. The ARMI Framework provides a `Material` class, which has a composition (how many of each nuclide are in the material), and a variety of thermome... | from armi.materials import uraniumOxide
uo2 = uraniumOxide.UO2()
density500 = uo2.density(Tc=500)
print(f"The density of UO2 @ T = 500C is {density500:.2f} g/cc") | _____no_output_____ | Apache-2.0 | doc/tutorials/materials_demo.ipynb | DennisYelizarov/armi |
Taking a look at the composition | print(uo2.p.massFrac) | _____no_output_____ | Apache-2.0 | doc/tutorials/materials_demo.ipynb | DennisYelizarov/armi |
The mass fractions of a material, plus its mass density, fully define the composition. Conversions between number density/fraction and mass density/fraction are handled on the next level up (on `Component`s), which we will explore soon.ARMI automatically thermally-expands materials based on their coefficients of linear... | L0 = 10.0
dLL = uo2.linearExpansionFactor(500,25)
L = L0 * (1+dLL)
print(f"Hot length is {L:.4f} cm")
| _____no_output_____ | Apache-2.0 | doc/tutorials/materials_demo.ipynb | DennisYelizarov/armi |
Let's plot the heat capacity as a function of temperature in K. | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Tk = np.linspace(300,2000)
heatCapacity = [uo2.heatCapacity(Tk=ti) for ti in Tk]
plt.plot(Tk, heatCapacity)
plt.title("$UO_2$ heat capacity vs. temperature")
plt.xlabel("Temperature (K)")
plt.ylabel("Heat capacity (J/kg-K)")
plt.grid(ls='--',alpha=0.... | _____no_output_____ | Apache-2.0 | doc/tutorials/materials_demo.ipynb | DennisYelizarov/armi |
Intro to Table Detection with Fast RCNNBy taking an ImageNet-pretrained model such as the VGG16, we can add a few more convolutional layers to construct an RPN, or region proposal network. This module extracts regions of interest, or RoIs, that inform a model on where to identify an object. When the RoIs are applied, ... | # Train Fast RCNN
import logging
import pprint
import mxnet as mx
import numpy as np
from rcnn.config import config, default, generate_config
from rcnn.symbol import *
from rcnn.core import callback, metric
from rcnn.core.loader import AnchorLoader
from rcnn.core.module import MutableModule
from rcnn.utils.load_data ... | _____no_output_____ | Apache-2.0 | example/rcnn/Moodys-Table-Detection.ipynb | SCDM/mxnet |
Inference - Lets run some predictions | vis = False
gpu = 0
epoch = 3
prefix = 'e2e'
ctx = mx.gpu(gpu)
symbol = get_vgg_test(num_classes=config.NUM_CLASSES, num_anchors=config.NUM_ANCHORS)
predictor = get_net(symbol, prefix, epoch, ctx)
img_file = tempfile.NamedTemporaryFile()
#url = 'http://images.all-free-download.com/images/graphiclarge/aeroplane_boein... | _____no_output_____ | Apache-2.0 | example/rcnn/Moodys-Table-Detection.ipynb | SCDM/mxnet |
Table Object Detection | import numpy as np
import matplotlib.pyplot as plt
im = np.array(Image.open('/home/ubuntu/workspace/mxnet/example/rcnn/new_data/marked_table.png'))
plt.imshow(im)
plt.show() | _____no_output_____ | Apache-2.0 | example/rcnn/Moodys-Table-Detection.ipynb | SCDM/mxnet |
Models ensemble to achieve better test metricsModels ensemble is a popular strategy in machine learning and deep learning areas to achieve more accurate and more stable outputs. A typical practice is:* Split all the training dataset into K folds.* Train K models with every K-1 folds data.* Execute inference on the te... | !python -c "import monai" || pip install -q "monai-weekly[ignite, nibabel, tqdm]" | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Setup imports | # Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, s... | MONAI version: 0.6.0rc1+23.gc6793fd0
Numpy version: 1.20.3
Pytorch version: 1.9.0a0+c3d40fd
MONAI flags: HAS_EXT = True, USE_COMPILED = False
MONAI rev id: c6793fd0f316a448778d0047664aaf8c1895fe1c
Optional dependencies:
Pytorch Ignite version: 0.4.5
Nibabel version: 3.2.1
scikit-image version: 0.15.0
Pillow version: 7... | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Setup data directoryYou can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. This allows you to save results and reuse downloads. If not specified a temporary directory will be used. | directory = os.environ.get("MONAI_DATA_DIRECTORY")
root_dir = tempfile.mkdtemp() if directory is None else directory
print(root_dir) | /workspace/data/medical
| Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Set determinism, logging, device | set_determinism(seed=0)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
device = torch.device("cuda:0") | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Generate random (image, label) pairsGenerate 60 pairs for the task, 50 for training and 10 for test. And then split the 50 pairs into 5 folds to train 5 separate models. | data_dir = os.path.join(root_dir, "runs")
if not os.path.exists(data_dir):
os.makedirs(data_dir)
for i in range(60):
im, seg = create_test_image_3d(
128, 128, 128, num_seg_classes=1, channel_dim=-1)
n = nib.Nifti1Image(im, np.eye(4))
nib.save(n, os.path.join(data_dir, f"img... | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Setup transforms for training and validation | train_transforms = Compose(
[
LoadImaged(keys=["image", "label"]),
AsChannelFirstd(keys=["image", "label"], channel_dim=-1),
ScaleIntensityd(keys=["image", "label"]),
RandCropByPosNegLabeld(
keys=["image", "label"],
label_key="label",
spatial_size=... | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Define CacheDatasets and DataLoaders for train, validation and test | num_models = 5
train_dss = [CacheDataset(
data=train_files[i],
transform=train_transforms) for i in range(num_models)]
train_loaders = [
DataLoader(
train_dss[i], batch_size=2, shuffle=True, num_workers=4)
for i in range(num_models)
]
val_dss = [CacheDataset(data=val_files[i], transform=val_tra... | 100%|██████████| 40/40 [00:01<00:00, 26.37it/s]
100%|██████████| 40/40 [00:01<00:00, 33.42it/s]
100%|██████████| 40/40 [00:01<00:00, 36.70it/s]
100%|██████████| 40/40 [00:00<00:00, 40.63it/s]
100%|██████████| 40/40 [00:00<00:00, 43.25it/s]
100%|██████████| 10/10 [00:00<00:00, 40.24it/s]
100%|██████████| 10/10 [00:00<00... | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Define a training process based on workflowsMore usage examples of MONAI workflows are available at: [workflow examples](https://github.com/Project-MONAI/tutorials/tree/master/modules/engines). | def train(index):
net = UNet(
dimensions=3,
in_channels=1,
out_channels=1,
channels=(16, 32, 64, 128, 256),
strides=(2, 2, 2, 2),
num_res_units=2,
).to(device)
loss = DiceLoss(sigmoid=True)
opt = torch.optim.Adam(net.parameters(), 1e-3)
val_post_trans... | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Execute 5 training processes and get 5 models | models = [train(i) for i in range(num_models)] | INFO:ignite.engine.engine.SupervisedTrainer:Engine run resuming from iteration 0, epoch 0 until 4 epochs
INFO:ignite.engine.engine.SupervisedTrainer:Epoch: 1/4, Iter: 1/20 -- train_loss: 0.6230
INFO:ignite.engine.engine.SupervisedTrainer:Epoch: 1/4, Iter: 2/20 -- train_loss: 0.5654
INFO:ignite.engine.engine.Supervise... | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Define evaluation process based on `EnsembleEvaluator` | def ensemble_evaluate(post_transforms, models):
evaluator = EnsembleEvaluator(
device=device,
val_data_loader=test_loader,
pred_keys=["pred0", "pred1", "pred2", "pred3", "pred4"],
networks=models,
inferer=SlidingWindowInferer(
roi_size=(96, 96, 96), sw_batch_size=... | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Evaluate the ensemble result with `MeanEnsemble``EnsembleEvaluator` accepts a list of models for inference and outputs a list of predictions for further operations.Here the input data is a list or tuple of PyTorch Tensor with shape: [B, C, H, W, D]. The list represents the output data from 5 models. And `MeanEnsembl... | mean_post_transforms = Compose(
[
EnsureTyped(keys=["pred0", "pred1", "pred2", "pred3", "pred4"]),
MeanEnsembled(
keys=["pred0", "pred1", "pred2", "pred3", "pred4"],
output_key="pred",
# in this particular example, we use validation metrics as weights
... | INFO:ignite.engine.engine.EnsembleEvaluator:Engine run resuming from iteration 0, epoch 0 until 1 epochs
INFO:ignite.engine.engine.EnsembleEvaluator:Got new best metric of test_mean_dice: 0.9435271978378296
INFO:ignite.engine.engine.EnsembleEvaluator:Epoch[1] Complete. Time taken: 00:00:02
INFO:ignite.engine.engine.Ens... | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Evaluate the ensemble result with `VoteEnsemble`Here the input data is a list or tuple of PyTorch Tensor with shape: [B, C, H, W, D]. The list represents the output data from 5 models.Note that:* `VoteEnsemble` expects the input data is discrete values.* Input data can be multiple channels data in One-Hot format or s... | vote_post_transforms = Compose(
[
EnsureTyped(keys=["pred0", "pred1", "pred2", "pred3", "pred4"]),
Activationsd(keys=["pred0", "pred1", "pred2",
"pred3", "pred4"], sigmoid=True),
# transform data into discrete before voting
AsDiscreted(keys=["pred0", "pred1... | INFO:ignite.engine.engine.EnsembleEvaluator:Engine run resuming from iteration 0, epoch 0 until 1 epochs
INFO:ignite.engine.engine.EnsembleEvaluator:Got new best metric of test_mean_dice: 0.9436934590339661
INFO:ignite.engine.engine.EnsembleEvaluator:Epoch[1] Complete. Time taken: 00:00:02
INFO:ignite.engine.engine.Ens... | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Cleanup data directoryRemove directory if a temporary was used. | if directory is None:
shutil.rmtree(root_dir) | _____no_output_____ | Apache-2.0 | modules/models_ensemble.ipynb | dzenanz/tutorials |
Load DatasetTo clear all record and load all images to the /dataset.svg_w=960, svg_h=540 | from app.models import Label,Image,Batch, Comment, STATUS_CHOICES
from django.contrib.auth.models import User
import os, fnmatch, uuid, shutil
from uuid import uuid4
def getbatchlist(filelist):
def chunks(li, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(li), n):
... | batch: BID000001,src: 15185e10-3d59-4129-b5c4-314fdb228a59.jpg, dst: 6c35c307-30ca-48c1-a92e-7b7dd9b60108.jpg
batch: BID000001,src: 25136c78-05f6-422c-9b82-cbbd42deb261.jpg, dst: ba0d77ca-d6da-4213-b396-944580bfccea.jpg
batch: BID000001,src: 34c84071-abd7-4f01-86e6-3f2dc6c96a0b.jpg, dst: 2ed9b9ed-bcec-45a2-a068-8806e9e... | MIT | beta/debug_load_imgaes.ipynb | SothanaV/visionmarker |
Orthogonal Matching PursuitUsing orthogonal matching pursuit for recovering a sparse signal from a noisymeasurement encoded with a dictionary | print(__doc__)
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import OrthogonalMatchingPursuit
from sklearn.linear_model import OrthogonalMatchingPursuitCV
from sklearn.datasets import make_sparse_coded_signal
n_components, n_features = 512, 100
n_nonzero_coefs = 17
# generate the data
... | _____no_output_____ | Apache-2.0 | 01 Machine Learning/scikit_examples_jupyter/linear_model/plot_omp.ipynb | alphaolomi/colab |
1. AutoGraph writes graph code for you[AutoGraph](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/autograph/README.md) helps you write complicated graph code using just plain Python -- behind the scenes, AutoGraph automatically transforms your code into the equivalent TF graph code. We support ... | # Autograph can convert functions like this...
def g(x):
if x > 0:
x = x * x
else:
x = 0.0
return x
# ...into graph-building functions like this:
def tf_g(x):
with tf.name_scope('g'):
def if_true():
with tf.name_scope('if_true'):
x_1, = x,
x_1 = x_1 * x_1
return x_1,
... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Automatically converting complex control flowAutoGraph can convert a large chunk of the Python language into equivalent graph-construction code, and we're adding new supported language features all the time. In this section, we'll give you a taste of some of the functionality in AutoGraph.AutoGraph will automatically ... | # Continue in a loop
def f(l):
s = 0
for c in l:
if c % 2 > 0:
continue
s += c
return s
print('Original value: %d' % f([10,12,15,20]))
tf_f = autograph.to_graph(f)
with tf.Graph().as_default():
with tf.Session():
print('Graph value: %d\n\n' % tf_f(tf.constant([10,12,15,20])).eval())
print(a... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Try replacing the `continue` in the above code with `break` -- AutoGraph supports that as well! Let's try some other useful Python constructs, like `print` and `assert`. We automatically convert Python `assert` statements into the equivalent `tf.Assert` code. | def f(x):
assert x != 0, 'Do not pass zero!'
return x * x
tf_f = autograph.to_graph(f)
with tf.Graph().as_default():
with tf.Session():
try:
print(tf_f(tf.constant(0)).eval())
except tf.errors.InvalidArgumentError as e:
print('Got error message:\n%s' % e.message) | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
You can also use plain Python `print` functions in in-graph | def f(n):
if n >= 0:
while n < 5:
n += 1
print(n)
return n
tf_f = autograph.to_graph(f)
with tf.Graph().as_default():
with tf.Session():
tf_f(tf.constant(0)).eval() | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Appending to lists in loops also works (we create a tensor list ops behind the scenes) | def f(n):
z = []
# We ask you to tell us the element dtype of the list
autograph.set_element_type(z, tf.int32)
for i in range(n):
z.append(i)
# when you're done with the list, stack it
# (this is just like np.stack)
return autograph.stack(z)
tf_f = autograph.to_graph(f)
with tf.Graph().as_default():
... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
De-graphify Exercises Easy print statements | # See what happens when you turn AutoGraph off.
# Do you see the type or the value of x when you print it?
# @autograph.convert()
def square_log(x):
x = x * x
print('Squared value of x =', x)
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(square_log(tf.constant(4)))) | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Convert the TensorFlow code into Python code for AutoGraph | def square_if_positive(x):
x = tf.cond(tf.greater(x, 0), lambda: x * x, lambda: x)
return x
with tf.Session() as sess:
print(sess.run(square_if_positive(tf.constant(4))))
@autograph.convert()
def square_if_positive(x):
pass # TODO: fill it in!
with tf.Session() as sess:
print(sess.run(square_if_positive(t... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Uncollapse to see answer | # Simple cond
@autograph.convert()
def square_if_positive(x):
if x > 0:
x = x * x
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(square_if_positive(tf.constant(4)))) | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Nested If statement | def nearest_odd_square(x):
def if_positive():
x1 = x * x
x1 = tf.cond(tf.equal(x1 % 2, 0), lambda: x1 + 1, lambda: x1)
return x1,
x = tf.cond(tf.greater(x, 0), if_positive, lambda: x)
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(nearest_odd_squa... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Uncollapse to reveal answer | @autograph.convert()
def nearest_odd_square(x):
if x > 0:
x = x * x
if x % 2 == 0:
x = x + 1
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(nearest_odd_square(tf.constant(4)))) | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Convert a while loop | # Convert a while loop
def square_until_stop(x, y):
x = tf.while_loop(lambda x: tf.less(x, y), lambda x: x * x, [x])
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(square_until_stop(tf.constant(4), tf.constant(100))))
@autograph.convert()
def square_until_stop(x, y):
pass... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Uncollapse for the answer | @autograph.convert()
def square_until_stop(x, y):
while x < y:
x = x * x
return x
with tf.Graph().as_default():
with tf.Session() as sess:
print(sess.run(square_until_stop(tf.constant(4), tf.constant(100)))) | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Nested loop and conditional | @autograph.convert()
def argwhere_cumsum(x, threshold):
current_sum = 0.0
idx = 0
for i in range(len(x)):
idx = i
if current_sum >= threshold:
break
current_sum += x[i]
return idx
n = 10
with tf.Graph().as_default():
with tf.Session() as sess:
idx = argwhere_cumsum(tf.ones(n), tf.const... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Uncollapse to see answer | @autograph.convert()
def argwhere_cumsum(x, threshold):
current_sum = 0.0
idx = 0
for i in range(len(x)):
idx = i
if current_sum >= threshold:
break
current_sum += x[i]
return idx
n = 10
with tf.Graph().as_default():
with tf.Session() as sess:
idx = argwhere_cumsum(tf.ones(n), tf.cons... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
3. Training MNIST in-graphWriting control flow in AutoGraph is easy, so running a training loop in a TensorFlow graph should be easy as well! Here, we show an example of training a simple Keras model on MNIST, where the entire training process -- loading batches, calculating gradients, updating parameters, calculatin... | import gzip
import os
import shutil
from six.moves import urllib
def download(directory, filename):
filepath = os.path.join(directory, filename)
if tf.gfile.Exists(filepath):
return filepath
if not tf.gfile.Exists(directory):
tf.gfile.MakeDirs(directory)
url = 'https://storage.googleapis.com/cvdf-dat... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Define the model | def mlp_model(input_shape):
model = tf.keras.Sequential((
tf.keras.layers.Dense(100, activation='relu', input_shape=input_shape),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')))
model.build()
return model
def predict(m, x, y):
y_p = m(x)
los... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
Define the training loop | def train(train_ds, test_ds, hp):
m = mlp_model((28 * 28,))
opt = tf.train.MomentumOptimizer(hp.learning_rate, 0.9)
# We'd like to save our losses to a list. In order for AutoGraph
# to convert these lists into their graph equivalent,
# we need to specify the element type of the lists.
train_losses = []
... | _____no_output_____ | Apache-2.0 | tensorflow/contrib/autograph/examples/notebooks/workshop.ipynb | nicolasoyharcabal/tensorflow |
!pip install yfinance
import yfinance
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
import datetime
plt.rcParams['figure.figsize'] = [10, 7]
plt.rc('font', size=14)
np.random.seed(0)
y = np.arange(0,100,1) + np.random.normal(0,10,100)
sma = pd.Series(y).rolli... | _____no_output_____ | MIT | Find_the_best_moving_average.ipynb | BiffTannon/Test | |
Numpy We have seen python basic data structures in our last section. They are great but lack specialized features for data analysis. Like, adding roows, columns, operating on 2d matrices aren't readily available. So, we will use *numpy* for such functions. | import numpy as np | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Numpy operates on *nd* arrays. These are similar to lists but contains homogenous elements but easier to store 2-d data. | l1 = [1,2,3,4]
nd1 = np.array(l1)
print(nd1)
l2 = [5,6,7,8]
nd2 = np.array([l1,l2])
print(nd2) | [1 2 3 4]
[[1 2 3 4]
[5 6 7 8]]
| Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Some functions on np.array() | print(nd2.shape)
print(nd2.size)
print(nd2.dtype) | (2, 4)
8
int32
| Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Question 1Create an identity 2d-array or matrix (with ones across the diagonal). | np.identity(2)
np.eye(2) | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Question 2Create a 2d-array or matrix of order 3x3 with values = 9,8,7,6,5,4,3,2,1 arranged in the same order. | d=np.matrix([[9,8,7],[6,5,4],[3,2,1]])
d
np.arange(9,0,-1).reshape(3,3) | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Question 3Reverse both the rows and columns of the given matrix. | d.T | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Question 4Add + 1 to all the elements in the given matrix. | d + 1 | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Similarly you can do operations like scalar substraction, division, multiplication (operating on each element in the matrix) Question 5Find the mean of all elements in the given matrix nd6.nd6 = [[ 1 4 9 121 144 169] [ 16 25 36 196 225 256] [ 49 64 81 289 324 361]] | nd6 = np.matrix([[ 1, 4, 9, 121, 144, 169], [ 16, 25, 36, 196, 225, 256], [ 49, 64, 81, 289, 324, 361]])
nd6.mean() | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Question 7Find the dot product of two given matrices. | mat1 = np.arange(9).reshape(3,3)
mat2 = np.arange(10,19,1).reshape(3,3)
mat1.dot(mat2)
mat1 @ mat2
np.dot(mat1, mat2) | _____no_output_____ | Apache-2.0 | CourseContent/03-Intro.to.Python.and.Basic.Statistics/Week1/Practice.Exercise/2.Lab - Numpy.ipynb | averma111/AIML-PGP |
Festival Playlists | import os
import numpy as np
import pandas as pd
import requests
import json
import spotipy
from IPython.display import display | _____no_output_____ | MIT | notebooks/using_APIs_to_automate_the_process.ipynb | adrialuzllompart/festival-playlists |
1. Use the Songkick API to get all the bands playing the festival2. Use the Setlist.FM API to get the setlists3. Use the Spotify API to create the playlists and add all the songs Set API credentials | setlistfm_api_key = os.getenv('SETLISTFM_API_KEY')
spotify_client_id = os.getenv('SPOTIFY_CLIENT_ID')
spotify_client_secret = os.getenv('SPOTIFY_CLIENT_SECRET') | _____no_output_____ | MIT | notebooks/using_APIs_to_automate_the_process.ipynb | adrialuzllompart/festival-playlists |
Setlist FM Plan of action1. Given a lineup (list of band names), get their Musicbrainz identifiers (`mbid`) via `https://api.setlist.fm/rest/1.0/search/artists`2. Retrieve the setlists for each artist using their `mbid` via `https://api.setlist.fm/rest/1.0/artist/{artist_mbid}/setlists` | lineup = pd.read_csv(
'/Users/adrialuz/Desktop/weekender.txt', header=None, names=['band'], encoding="ISO-8859-1"
)['band'].values
len(lineup)
lineup
artists_url = 'https://api.setlist.fm/rest/1.0/search/artists'
lineup_mbids = []
not_found = []
for name in lineup:
req = requests.get(artists_url,
... | _____no_output_____ | MIT | notebooks/using_APIs_to_automate_the_process.ipynb | adrialuzllompart/festival-playlists |
Spotify | username = 'adrialuz'
scope = 'playlist-modify-public'
token = spotipy.util.prompt_for_user_token(username, scope, redirect_uri='http://localhost:9090')
sp = spotipy.Spotify(auth=token)
sp.trace = False
sp.search('artist:Dua Lipa', limit=1, type='artist', market='GB')['artists']['items'][0]['id']
sp.search(
... | _____no_output_____ | MIT | notebooks/using_APIs_to_automate_the_process.ipynb | adrialuzllompart/festival-playlists |
Get the URI codes for each track | uris = []
missing_songs = []
for a in (artist_setlist + popular_songs):
artist = a['artist']
setlist = a['setlist']
for s in setlist:
s = s.replace(',', '').replace('\'', '').replace('"', '').replace('.', '').replace(
'?', '').replace(')', '').replace('(', '').replace('/', '').replace(
... | _____no_output_____ | MIT | notebooks/using_APIs_to_automate_the_process.ipynb | adrialuzllompart/festival-playlists |
Error HandlingThe code in this notebook helps with handling errors. Normally, an error in notebook code causes the execution of the code to stop; while an infinite loop in notebook code causes the notebook to run without end. This notebook provides two classes to help address these concerns. **Prerequisites*** This... | import bookutils
import traceback
import sys
from types import FrameType, TracebackType
# ignore
from typing import Union, Optional, Callable, Any
class ExpectError:
"""Execute a code block expecting (and catching) an error."""
def __init__(self, exc_type: Optional[type] = None,
print_traceba... | _____no_output_____ | MIT | docs/notebooks/ExpectError.ipynb | bjrnmath/debuggingbook |
Here's an example: | def fail_test() -> None:
# Trigger an exception
x = 1 / 0
with ExpectError():
fail_test()
with ExpectError(print_traceback=False):
fail_test() | ZeroDivisionError: division by zero (expected)
| MIT | docs/notebooks/ExpectError.ipynb | bjrnmath/debuggingbook |
We can specify the type of the expected exception. This way, if something else happens, we will get notified. | with ExpectError(ZeroDivisionError):
fail_test()
with ExpectError():
with ExpectError(ZeroDivisionError):
some_nonexisting_function() # type: ignore | Traceback (most recent call last):
File "<ipython-input-1-e6c7dad1986d>", line 3, in <module>
some_nonexisting_function() # type: ignore
File "<ipython-input-1-e6c7dad1986d>", line 3, in <module>
some_nonexisting_function() # type: ignore
NameError: name 'some_nonexisting_function' is not defined (expecte... | MIT | docs/notebooks/ExpectError.ipynb | bjrnmath/debuggingbook |
Catching TimeoutsThe class `ExpectTimeout(seconds)` allows to express that some code may run for a long or infinite time; execution is thus interrupted after `seconds` seconds. A typical usage looks as follows:```Pythonfrom ExpectError import ExpectTimeoutwith ExpectTimeout(2) as t: function_that_is_supposed_to_ha... | import sys
import time
class ExpectTimeout:
"""Execute a code block expecting (and catching) a timeout."""
def __init__(self, seconds: Union[int, float],
print_traceback: bool = True, mute: bool = False):
"""
Constructor. Interrupe execution after `seconds` seconds.
If... | _____no_output_____ | MIT | docs/notebooks/ExpectError.ipynb | bjrnmath/debuggingbook |
Here's an example: | def long_running_test() -> None:
print("Start")
for i in range(10):
time.sleep(1)
print(i, "seconds have passed")
print("End")
with ExpectTimeout(5, print_traceback=False):
long_running_test() | Start
0 seconds have passed
1 seconds have passed
2 seconds have passed
3 seconds have passed
| MIT | docs/notebooks/ExpectError.ipynb | bjrnmath/debuggingbook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.