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
In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one)...
from sagemaker.pytorch import PyTorch estimator = PyTorch(entry_point="train.py", source_dir="train", role=role, framework_version='0.4.0', train_instance_count=1, train_instance_type='ml.p2.xlarge', ...
2019-10-30 08:56:36 Starting - Starting the training job... 2019-10-30 08:56:39 Starting - Launching requested ML instances...... 2019-10-30 08:57:45 Starting - Preparing the instances for training...... 2019-10-30 08:59:05 Downloading - Downloading input data...... 2019-10-30 08:59:41 Training - Downloading the traini...
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Step 5: Testing the modelAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly. Step 6: Deploy the model for testingNow that we have ...
# TODO: Deploy the trained model predictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.m4.xlarge')
---------------------------------------------------------------------------------------------------!
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Step 7 - Use the model for testingOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is.
test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1) # We split the data into chunks and send each chunk seperately, accumulating the results. def predict(data, rows=512): split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1)) predictions = np.array([]) for array in...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis? **Answer:** The performance of this RNN model is comparable to the XGBoost model. However, this RNN model is is relat...
test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.'
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
The question we now need to answer is, how do we send this review to our model?Recall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews. - Removed any html tags and stemmed the input - Encoded the review as a se...
# TODO: Convert test_review into a form usable by the model and save the results in test_data test_data = None test_words = review_to_words(test_review) test_numerical, length = convert_and_pad(word_dict, test_words) test_data = np.array([[length] + test_numerical])
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.
predictor.predict(test_data)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive. Delete the endpointOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delet...
estimator.delete_endpoint()
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Step 6 (again) - Deploy the model for the web appNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.As we saw above, by default the estimator which we created, w...
!pygmentize serve/predict.py
import argparse import json import os import pickle import sys import sagemaker_containers ...
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.**TODO**: Complete th...
from sagemaker.predictor import RealTimePredictor from sagemaker.pytorch import PyTorchModel class StringPredictor(RealTimePredictor): def __init__(self, endpoint_name, sagemaker_session): super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain') model = PyTorchMode...
---------------------------------------------------------------------------------------------------!
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Testing the modelNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is t...
import glob def test_reviews(data_dir='../data/aclImdb', stop=250): results = [] ground = [] # We make sure to test both positive and negative reviews for sentiment in ['pos', 'neg']: path = os.path.join(data_dir, 'test', sentiment, '*.txt') files = glob.glob(path)...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
As an additional test, we can try sending the `test_review` that we looked at earlier.
predictor.predict(test_review)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back. Step 7 (again): Use the model for th...
predictor.endpoint
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function. Setting up API GatewayNow that our Lambda function is set up, it is time to create a new API using API Gateway that wi...
predictor.delete_endpoint()
_____no_output_____
MIT
Project/SageMaker Project.ipynb
kurdi1mans/sagemaker-deployment-project
**Tansfer Learning for Classification of Horses and Humans** **Abstract**Aim of the notebook is to demonstrate the use of the transfer learning for improving the model accuracy for real-world images.
import os import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras import Model from os import getcwd path_inception = f"{getcwd()}/../tmp2/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5" from tensorflow.keras.applications.inception_v3 import InceptionV3 local_weights_file = path_i...
_____no_output_____
MIT
3.Horses_vs_humans_using_Transfer_Learning.ipynb
Abhishek-Gargha-Maheshwarappa/Deeplearning-Basic-
Let's design a LNA using Infineon's BFU520 transistor. First we need to import scikit-rf and a bunch of other utilities:
import numpy as np import skrf from skrf.media import DistributedCircuit import skrf.frequency as freq import skrf.network as net import skrf.util import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = [10, 10] f = freq.Frequency(0.4, 2, 101) tem = DistributedCircuit(f, z0=50) # import...
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
Let's plot the smith chart for it:
bjt.plot_s_smith()
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
Now let's calculate the source and load stablity curves.I'm slightly misusing the `Network` type to plot the curves; normally the curves you pass in to `Network` should be a function of frequency, but it also works to draw these circles as long as you don't try to use any other functions on them
sqabs = lambda x: np.square(np.absolute(x)) delta = bjt.s11.s*bjt.s22.s - bjt.s12.s*bjt.s21.s rl = np.absolute((bjt.s12.s * bjt.s21.s)/(sqabs(bjt.s22.s) - sqabs(delta))) cl = np.conj(bjt.s22.s - delta*np.conj(bjt.s11.s))/(sqabs(bjt.s22.s) - sqabs(delta)) rs = np.absolute((bjt.s12.s * bjt.s21.s)/(sqabs(bjt.s11.s) - sq...
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
So we can see that we need to avoid inductive loads near short circuit in the input matching network and high impedance inductive loads on the output.Let's draw some constant noise circles. First we grab the noise parameters for our target frequency from the network model:
idx_915mhz = skrf.util.find_nearest_index(bjt.f, 915.e+6) # we need the normalized equivalent noise and optimum source coefficient to calculate the constant noise circles rn = bjt.rn[idx_915mhz]/50 gamma_opt = bjt.g_opt[idx_915mhz] fmin = bjt.nfmin[idx_915mhz] for nf_added in [0, 0.1, 0.2, 0.5]: nf = 10**(nf_adde...
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
So we can see from the chart that just leaving the input at 50 ohms gets us under 0.1 dB of extra noise, which seems pretty good. I'm actually not sure that these actually correspond to the noise figure level increments I have listed up there, but the circles should at least correspond to increasing noise figuresSo let...
gamma_s = 0.0 gamma_l = np.conj(bjt.s22.s - bjt.s21.s*gamma_s*bjt.s12.s/(1-bjt.s11.s*gamma_s)) gamma_l = gamma_l[idx_915mhz, 0, 0] is_gamma_l_stable = np.absolute(gamma_l - cl[idx_915mhz]) > rl[idx_915mhz] gamma_l, is_gamma_l_stable
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
This looks like it may be kind of close to the load instability circles, so it might make sense to pick a load point with less gain for more stability, or to pick a different source impedance with more noise.But for now let's just build a matching network for this and see how it performs:
def calc_matching_network_vals(z1, z2): flipped = np.real(z1) < np.real(z2) if flipped: z2, z1 = z1, z2 # cancel out the imaginary parts of both input and output impedances z1_par = 0.0 if abs(np.imag(z1)) > 1e-6: # parallel something to cancel out the imaginary part of ...
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
Let's calculate what the component values are:
c_par = np.real(1/(2j*np.pi*915e+6*z_par)) l_ser = np.real(z_ser/(2j*np.pi*915e+6)) c_par, l_ser
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
The capacitance is kind of low but the inductance seems reasonable. Let's test it out:
output_network = tem.shunt_capacitor(c_par) ** tem.inductor(l_ser) amplifier = bjt ** output_network amplifier.plot_s_smith()
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
That looks pretty reasonable; let's take a look at the S21 to see what we got:
amplifier.s21.plot_s_db()
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
So about 18 dB gain; let's see what our noise figure is:
10*np.log10(amplifier.nf(50.)[idx_915mhz])
_____no_output_____
BSD-3-Clause
doc/source/tutorials/LNA Example.ipynb
boxyrobot/scikit-rf
Carbon Dioxide Analysis
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Read Website from urllib.request import urlopen def read_url(url): print(urlopen(url).read().decode()) read_url("ftp://aftp.cmdl.noaa.gov/products/trends/co2/co2_mm_mlo.txt") ## Import the data in table format: df = pd.read_table("ftp://aftp...
_____no_output_____
MIT
Global_Warmth_NASA/Carbon_Dioxide_fbprophet.ipynb
LastAncientOne/Kaggle-Project
Forecast CO2
from fbprophet import Prophet df1 = df.copy() df1['Date'] = pd.to_datetime(df.year.astype(str) + '-' + df.month.astype(str)) df1 = df1.rename(index=str, columns={"Date": "ds", "trend": "y"}) df1.head() df1 = df1.drop(['year','month','decimal_date','average','interpolated','days'], axis=1) df1 = df1[['ds', 'y']] # Norma...
_____no_output_____
MIT
Global_Warmth_NASA/Carbon_Dioxide_fbprophet.ipynb
LastAncientOne/Kaggle-Project
Model Selection ![Data Science Workflow](img/ds-workflow.png) Model Selection- The process of selecting the model among a collection of candidates machine learning models Problem type- What kind of problem are you looking into? - **Classification**: *Predict labels on data with predefined classes* - Supervi...
import pandas as pd data = pd.read_parquet('files/house_sales.parquet') data.head() data.describe() data['SalePrice'].plot.hist(bins=20)
_____no_output_____
MIT
Data Science With Python/13 - Lesson - Model Selection.ipynb
shreejitverma/Data-Scientist
Converting to Categories- [`cut()`](https://pandas.pydata.org/docs/reference/api/pandas.cut.html) Bin values into discrete intervals. - Data in bins based on data distribution.- [`qcut()`](https://pandas.pydata.org/docs/reference/api/pandas.qcut.html) Quantile-based discretization function. - Data in equal size ...
data['Target'] = pd.cut(data['SalePrice'], bins=3, labels=[1, 2, 3]) data['Target'].value_counts()/len(data) data['Target'] = pd.qcut(data['SalePrice'], q=3, labels=[1, 2, 3]) data['Target'].value_counts()/len(data) from sklearn.model_selection import train_test_split from sklearn.svm import SVC, LinearSVC from sklearn...
_____no_output_____
MIT
Data Science With Python/13 - Lesson - Model Selection.ipynb
shreejitverma/Data-Scientist
ACTUAL
import pretty_midi import pandas as pd path = "MAPS.mid" midi_data = pretty_midi.PrettyMIDI(path) midi_list = [] pretty_midi.pretty_midi.MAX_TICK = 1e10 midi_data.tick_to_time(14325216) for instrument in midi_data.instruments: for note in instrument.notes: start = note.start end = note.end ...
_____no_output_____
MIT
MODEL - 1 (RNN)/Raw/Post_Processing_RNN.ipynb
rrustagi20/Deep-learning---Automatic-Music-Transcription
Active Testing Using Text Data This is an example of using the ActT library with a text dataset. To walk through this example, download __[a sentiment analysis dataset](https://archive.ics.uci.edu/ml/machine-learning-databases/00331/)__ from the UCI machine learning repository and place the contents in the text_data ...
create_datasets = False # get rid of temporary files inserted to preserve directory structure if create_datasets: myfile = 'text_data/temp.txt' if os.path.isfile(myfile): os.remove(myfile) myfile = 'train/positive/temp.txt' if os.path.isfile(myfile): os.remove(myfile) myfile = 'train...
_____no_output_____
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Loading Data and Training a Model Below, we load the training data, create term frequency features, and then fit a classifier to the data.
#Load training data from files categories = ['positive', 'negative'] sent_data = datasets.load_files(container_path='train', categories=categories, shuffle=True) X_train, y_train = sent_data.data, sent_data.target #Extract features count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(X_train) #Tra...
_____no_output_____
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Now, we transform the test dataset to use the same features, apply the classifier to the test dataset and compute the classifier's true accuracy.
#Load the test data from files sent_data_test = datasets.load_files(container_path='test', categories=categories, shuffle=False) X_test, y_test = sent_data_test.data, sent_data_test.target #Extract features X_test_counts = count_vect.transform(sent_data_test.data) #Transform occurance matrix to a frequency matrix X_t...
_____no_output_____
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Using Active TesterThe following code creates a set of noisy labels, reshapes the true labels, and converts the test features to a dense array.
#Initialize key variables: X, Y_noisy, and vetted Y_noisy = [] noisy_label_accuracy = 0.75 for i in range(len(y_test)): if np.random.rand() < noisy_label_accuracy: # noisy label is correct Y_noisy.append(y_test[i]) else: # noisy label is incorrect Y_noisy.append(np.random.choice(...
_____no_output_____
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Now to display the sentences to the vetter in an interactive session, we need to create a list of all the test data files. This will serve as raw input to the `query_vetted` method of `active_tester`.
#Create a list with all of the test data files to serve as the raw input to query vetted file_list = [] sentence_dirs = os.path.join(os.getcwd(),'test') for root, dirs, files in os.walk(sentence_dirs): for name in files: if name.endswith('.txt'): local_path = os.path.join(root, name) ...
_____no_output_____
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Now, we are ready to estimate the performance of the classifier by querying the oracle.
#Active Tester with a Naive Estimator, Classifier Uncertainty Query Method, and Interactive Query Vetting budget = 5 active_test = ActiveTester(Naive(metric=accuracy_score), ClassifierUncertainty()) active_test.standardize_data(X=X, classes=sent_d...
Test metric with budget of 5 : 0.6368715083798883 True accuracy of classifier: 0.7620111731843575
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
A Comparison of Query Strategies and EstimatorsBelow, we compare a couple of query strategies and estimators.
import matplotlib.pyplot as plt abs_error_array = [] # Initialize the estimators learned = Learned(metric=accuracy_score, estimation_method=oracle_multiple_labels) naive = Naive(metric=accuracy_score) estimator_list = {'Naive': naive, 'Learned': learned} # Initialize a few query strategies rand = Random() classifier...
Beginning preprocessing to find vetted labels of each class... Completed preprocessing Budget reduced from "100" to "98" Beginning preprocessing to find vetted labels of each class... Completed preprocessing Budget reduced from "200" to "198" Beginning preprocessing to find vetted labels of each class... Completed prep...
BSD-3-Clause
notebooks/Text Data.ipynb
rlbellaire/ActT
Running Plato in Google's Colab Notebooks 1. Preparation Use Chrome broswerSince Colab is a product from Google, to take the most advantage of it, Chrome is the most recommended broswer here. Activating GPU supportIf you need GPU support in your project, you may activate it in Google Colab by clicking on `Runtime > Ch...
import torch torch.cuda.is_available()
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
If successful, the output of the cell above should print `True`. Use Google DriveSince Google Colab removes all the files that you have downloaded or created when you end a session, the best option is to use GitHub to store your code, and Google Drive to store your datasets, logs, and anything else that would normally ...
from google.colab import drive drive.mount('/content/drive') root_path = '/content/drive/My\ Drive' %cd $root_path
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
2. Installing Plato with PyTorchClone Plato's public git repository on GitHub to your Google drive.
!git clone https://github.com/TL-System/plato
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
Then install the required Python packages:
!pip install -r $root_path/plato/requirements.txt -U
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
Get into the `plato` directory:
!chmod -R ugo+rx $root_path/plato/run %cd $root_path/plato/
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
3. Running Plato Make sure you don’t get disconnectedRun the following cell when you plan to do a long training to avoid getting disconnected in the middle of it.
%%javascript function ClickConnect(){ console.log("Working"); document.querySelector("colab-toolbar-button#connect").click() }setInterval(ClickConnect,60000)
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
**Note:** Please use this responsibly. Getting booted from Colab is very annoying, but it is done to make resources available for others when you’re not actively using them. Setting up Weights and BiasesSupport for logging using Weights and Biases (https://wandb.com) is built-in. It will prompt you to enter your key ...
!wandb offline
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
Running Plato in the Colab notebookTo start a federated learning training workload, run `run` from Plato's home directory. For example:
!./run -s 127.0.0.1:8000 -c ./configs/MNIST/fedavg_lenet5.yml
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
Here, `fedavg_lenet5.yml` is a sample configuration file that uses Federated Averaging as the federated learning algorithm, and LeNet5 as the model. Other configuration files under `plato/configs/` could also be used here. Running Plato in a terminalIt is strongly recommended and more convenient to run Plato in a term...
!pip install colab_ssh --upgrade from getpass import getpass ngrok_token = getpass('Your authentication token: ') password = getpass('Your ngrok account password: ') from colab_ssh import launch_ssh, init_git launch_ssh(ngrok_token, password)
_____no_output_____
Apache-2.0
examples/plato_colab.ipynb
iQua/plato
Swift MNIST ExampleLearn more from Github: https://github.com/huan/tensorflow-handbook-swift MNIST Dataset
%install-location $cwd/swift-install %install '.package(url: "https://github.com/huan/swift-MNIST", from: "0.4.0")' MNIST
Installing packages: .package(url: "https://github.com/huan/swift-MNIST", from: "0.4.0") MNIST With SwiftPM flags: [] Working in: /tmp/tmpdu69j2gk/swift-install Fetching https://github.com/huan/swift-MNIST Cloning https://github.com/huan/swift-MNIST Resolving https://github.com/huan/swift-MNIST at 0.4.0 [1/2] Compil...
Apache-2.0
tensorflow-handbook-swift-example.ipynb
huan/swift-concise-mnist
Define a Simple MLP Model
import TensorFlow import Python import Foundation struct MLP: Layer { typealias Input = Tensor<Float> typealias Output = Tensor<Float> var flatten = Flatten<Float>() var dense = Dense<Float>(inputSize: 784, outputSize: 10) @differentiable public func callAsFunction(_ input: Input) -> Output { var x...
_____no_output_____
Apache-2.0
tensorflow-handbook-swift-example.ipynb
huan/swift-concise-mnist
Training
import MNIST let mnist = MNIST() let ((trainImages, trainLabels), (testImages, testLabels)) = mnist.loadData() let imageBatch = Dataset(elements: trainImages).batched(32) let labelBatch = Dataset(elements: trainLabels).batched(32) for (X, y) in zip(imageBatch, labelBatch) { // Caculate the gradient // let (_loss...
Downloading train-images-idx3-ubyte ... Downloading train-labels-idx1-ubyte ... Reading data. Constructing data tensors. Test Accuracy: 0.9125
Apache-2.0
tensorflow-handbook-swift-example.ipynb
huan/swift-concise-mnist
Tutorial 1: Instatiating a *scenario category*In this tutorial, we will cover the following items:1. Create *actor categories*, *activity categories*, and *physical thing categories*2. Instantiate a *scenario category*3. Show all tags of the *scenario category*4. Use the `includes` function of a *scenario category*5. ...
# Before starting, let us do the necessary imports import os import json from domain_model import ActorCategory, ActivityCategory, Constant, ScenarioCategory, \ Sinusoidal, Spline3Knots, StateVariable, PhysicalElementCategory, Tag, VehicleType, \ actor_category_from_json, scenario_category_from_json
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
1. Create *actor categories*, *activity categories*, and the *static physical thing categories*In this tutorial, we will create a *scenario category* in which another vehicle changes lane such that it becomes the ego vehicle's leading vehicle. This is often referred to as a "cut-in scenario". The *scenario category* i...
EGO_VEHICLE = ActorCategory(VehicleType.Vehicle, name="Ego vehicle", tags=[Tag.EgoVehicle, Tag.RoadUserType_Vehicle]) TARGET_VEHICLE = ActorCategory(VehicleType.Vehicle, name="Target vehicle", tags=[Tag.RoadUserType_Vehicle])
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
It is as simple as that. If it does not throw an error, you can be assured that a correct *actor category* is created. For example, if we would forget to add the brackets around the `Tag.RoadUserType_Vehicle` - such that it would not be a *list* of `Tag` - an error will be thrown:
# The following code results in an error! # The error is captured as to show only the final error message. try: ActorCategory(VehicleType.Vehicle, name="Target vehicle", tags=Tag.RoadUserType_Vehicle) except TypeError as error: print(error)
Input 'tags' should be of type typing.List but is of type <enum 'Tag'>.
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
Now let us create the *activity categories*:
FOLLOWING_LANE = ActivityCategory(Constant(), StateVariable.LATERAL_POSITION, name="Following lane", tags=[Tag.VehicleLateralActivity_GoingStraight]) CHANGING_LANE = ActivityCategory(Sinusoidal(), StateVariable.LATERAL_POSITION, ...
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
The last object we need to define before we can define the *scenario category* is the *static physical thing category*. A *scenario category* may contain multiple *physical things*, but for now we only define one that specifies the road layout. We assume that the scenario takes place at a straight motorway with multipl...
MOTORWAY = PhysicalElementCategory(description="Motorway with multiple lanes", name="Motorway", tags=[Tag.RoadLayout_Straight, Tag.RoadType_PrincipleRoad_Motorway])
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
2. Instantiate a *scenario category*To define a *scenario category*, we need a description and a location to an image. After this, the static content of the scenario can be specified using the `set_physical_things` function. Next, to describe the dynamic content of the scenarios, the *actor categories* can be passed u...
CUTIN = ScenarioCategory("./examples/images/cut-in.png", description="Cut-in at the motorway", name="Cut-in") CUTIN.set_physical_elements([MOTORWAY]) CUTIN.set_actors([EGO_VEHICLE, TARGET_VEHICLE]) CUTIN.set_activities([FOLLOWING_LANE, CHANGING_LANE, DRIVING_FORWARD]) C...
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
3. Show all tags of the *scenario category*The tags should be used to define the *scenario category* in such a manner that also a computer can understand. However, we did not pass any tags to the *scenario category* itself. On the other hand, the attributes of the *scenario category* (in this case, the *physical thing...
CUTIN.derived_tags()
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
Another way - and possibly easier way - to show the tags, is to simply print the scenario category. Doing this will show the name, the description, and all tags of the scenario category.
print(CUTIN)
Name: Cut-in Description: Cut-in at the motorway Tags: ├─ Ego vehicle::ActorCategory │ ├─ EgoVehicle │ ├─ RoadUserType_Vehicle │ ├─ VehicleLongitudinalActivity_DrivingForward │ └─ VehicleLateralActivity_GoingStraight ├─ Target vehicle::ActorCategory │ ├─ RoadUserType_Vehicle │ ├─ VehicleLongitudinalActivity_...
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
4. Use the *includes* function of a *scenario category*A *scenario category* A includes another *scenario category* B if it comprises all scenarios that are comprised in B. Loosely said, this means that *scenario category* A is "more general" than *scenario category* B. To demonstrate this, let us first create another...
CHANGING_LANE_RIGHT = ActivityCategory(Sinusoidal(), StateVariable.LATERAL_POSITION, name="Changing lane right", tags=[Tag.VehicleLateralActivity_ChangingLane_Right]) CUTIN_LEFT = ScenarioCategory("./examples/images/cut-in.png", ...
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
To ensure ourselves that we correctly created a new *scenario category*, we can print the scenario category. Note the difference with the previously defined *scenario category*: now the target vehicle performs a right lane change (see the tag `VehicleLateralActivity_ChangingLane_Right`).
print(CUTIN_LEFT)
Name: Cut-in from left Description: Cut-in from the left at the motorway Tags: ├─ Ego vehicle::ActorCategory │ ├─ EgoVehicle │ ├─ RoadUserType_Vehicle │ ├─ VehicleLongitudinalActivity_DrivingForward │ └─ VehicleLateralActivity_GoingStraight ├─ Target vehicle::ActorCategory │ ├─ RoadUserType_Vehicle │ ├─ V...
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
Because our original *scenario category* (`CUTIN`) is more general than the *scenario category* we just created (`CUTIN_LEFT`), we expect that `CUTIN` *includes* `CUTIN_LEFT`. In other words: because all "cut ins from the left" are also "cut ins", `CUTIN` *includes* `CUTIN_LEFT`.The converse is not true: not all "cut i...
print(CUTIN.includes(CUTIN_LEFT)) # True print(CUTIN_LEFT.includes(CUTIN)) # False
True False
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
5. Export the objectsIt would be cumbersome if one would be required to define a scenario category each time again. Luckily, there is an easy way to export the objects we have created. Each object of this domain model comes with a `to_json` function and a `to_json_full` function. These functions return a dictionary th...
CUTIN.to_json()
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
As can be seen, the *physical thing category* (see `physical_thing_categories`) only returns the `name` and `uid`. This is not enough information for us if we would like to recreate the *physical thing category*. Therefore, for now we will use the `to_json_full` functionality. Note, however, that if we would like to st...
FILENAME = os.path.join("examples", "cutin_qualitative.json") with open(FILENAME, "w") as FILE: json.dump(CUTIN.to_json_full(), FILE, indent=4)
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
Let us also save the other *scenario category*, such that we can use it for a later tutorial.
FILENAME_CUTIN_LEFT = os.path.join("examples", "cutin_left_qualitative.json") with open(FILENAME_CUTIN_LEFT, "w") as FILE: json.dump(CUTIN_LEFT.to_json_full(), FILE, indent=4)
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
So how can we use this .json code to create the *scenario category*? As each object has a `to_json_full` function, for each object there is a `_from_json` function. For the objects discussed in this toturial, we have:- for a *physical thing category*: `physical_thing_category_from_json`- for an *actor category*: `actor...
with open(FILENAME, "r") as FILE: CUTIN2 = scenario_category_from_json(json.load(FILE))
_____no_output_____
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
To see that this returns a similar *scenario category* as our previously created `CUTIN`, we can print the just created scenario category:
print(CUTIN2)
Name: Cut-in Description: Cut-in at the motorway Tags: ├─ Ego vehicle::ActorCategory │ ├─ EgoVehicle │ ├─ RoadUserType_Vehicle │ ├─ VehicleLongitudinalActivity_DrivingForward │ └─ VehicleLateralActivity_GoingStraight ├─ Target vehicle::ActorCategory │ ├─ RoadUserType_Vehicle │ ├─ VehicleLongitudinalActivity_...
MIT
Tutorial 1 Scenario category.ipynb
quepas/ScenarioDomainModel
New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-pl...
import plotly import plotly.plotly as py import plotly.tools as tls import plotly.graph_objs as go from plotly.grid_objs import Column, Grid from datetime import datetime as dt import numpy as np from IPython.display import Image column_1 = Column(['可以', '不可以', '随便'], '第一列') column_2 = Column([1, 2, 3], '第二列') # Tabu...
https://plot.ly/~yutianc/29/
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
View and Share your GridYou can view your newly created grid at the `url`:
Image('view_grid_url.png')
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
You are also able to view the grid in your list of files inside your [organize folder](https://plot.ly/organize). Upload Dataframes to PlotlyAlong with uploading a grid, you can upload a Dataframe as well as convert it to raw data as a grid:
import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv') df_head = df.head() table = ff.create_table(df_head) py.iplot(table, filename='dataframe_ex_preview', oa) grid = Grid([Column(df[column_na...
https://plot.ly/~chelsea_lyn/17399/
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
Making Graphs from GridsPlotly graphs are usually described with data embedded in them. For example, here we place `x` and `y` data directly into our `Histogram2dContour` object:
x = np.random.randn(1000) y = np.random.randn(1000) + 1 data = [ go.Histogram2dContour( x=x, y=y ) ] py.iplot(data, filename='Example 2D Histogram Contour')
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
We can also create graphs based off of references to columns of grids. Here, we'll upload several `column`s to our Plotly account:
column_1 = Column(np.random.randn(1000), 'column 1') column_2 = Column(np.random.randn(1000)+1, 'column 2') column_3 = Column(np.random.randn(1000)+2, 'column 3') column_4 = Column(np.random.randn(1000)+3, 'column 4') grid = Grid([column_1, column_2, column_3, column_4]) #url = py.grid_ops.upload(grid, filename='randn...
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
Make Graph from Raw DataInstead of placing data into `x` and `y`, we'll place our Grid columns into `xsrc` and `ysrc`:
data = [ go.Histogram2dContour( xsrc=grid[0], ysrc=grid[1] ) ] py.iplot(data, filename='2D Contour from Grid Data')
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
So, when you view the data, you'll see your original grid, not just the columns that compose this graph: Attaching Meta Data to GridsIn [Plotly Enterprise](https://plot.ly/product/enterprise/), you can upload and assign free-form JSON `metadata` to any grid object. This means that you can keep all of your raw data in ...
meta = { "Month": "November", "Experiment ID": "d3kbd", "Operator": "James Murphy", "Initial Conditions": { "Voltage": 5.5 } } #grid_url = py.grid_ops.upload(grid, filename='grid_with_metadata_'+str(dt.now()), meta=meta) grid_url = py.grid_ops.upload(grid, filename='grid_with_metadata', m...
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
Reference
help(py.grid_ops) from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_stat...
_____no_output_____
CC-BY-3.0
_posts/python/fundamentals/data-api/grid-api.ipynb
yutianc/plotly_documents
Python course Day 4 Dictionaries
student = {"number": 570, "name":"Simon", "age":23, "height":165} print(student) print(student['name']) print(student['age']) my_list = {1: 23, 2:56, 3:78, 4:14, 5:67} my_list[1] my_list.keys() my_list.values() student.keys() student.values() student['number'] = 111 print(student) student.items() # Iterate over a list ...
0 : 23 1 : 45 2 : 12 3 : 67 4 : 88 5 : 34 6 : 11
Apache-2.0
Lecture-Notes/2019/PSS-2019-Day4.ipynb
unmeshvrije/python-for-beginners
List Comprehension
# Pythonic ways to create lists # 1 numbers = [] for i in range(1,101): numbers.append(i) #1 ''' numbers contains all i's such that i takes value in range(1,101) ''' numbers = [i for i in range(1, 101)] print(numbers) def square(num): return num ** 2 square(5) #2. call a function to make list of squares of numb...
good better best
Apache-2.0
Lecture-Notes/2019/PSS-2019-Day4.ipynb
unmeshvrije/python-for-beginners
Now comparing with Random Forest Classifier instead of MultinomialNB. Stop here if you dont want to do the ahead steps Skip to 'save to csv' step
pipelineRf.fit(messages['Message'], messages['Label']) predictionsRf = pipelineRf.predict(messages['Message']) confusion_matrix(messages['Label'], predictionsRf) print(classification_report(messages['Label'], predictionsRf)) predictionsRf predictionsDf = pd.DataFrame(predictions, columns=['Naive Bayes Prediction']) pre...
_____no_output_____
MIT
NLP_Spam_MessagesG.ipynb
Vedant1202/ML_SpamMessagesFilter
Using Hyperopt to optimize XGB model hyperparameters Importing the libraries and loading the data
#!pip install --upgrade tables #!pip install eli5 #!pip install xgboost #!pip install hyperopt import numpy as np import pandas as pd import xgboost as xgb from sklearn.metrics import mean_absolute_error as mae from sklearn.model_selection import cross_val_score from hyperopt import hp, fmin, tpe, STATUS_OK import ...
_____no_output_____
MIT
day5_hyperopt.ipynb
marta-0/dw_matrix_cars
Feature Engineering
SUFFIX_CAT = '_cat' for feat in df.columns: if isinstance(df[feat][0], list): continue factorized_values = df[feat].factorize()[0] if SUFFIX_CAT in feat: df[feat] = factorized_values else: df[feat + SUFFIX_CAT] = factorized_values df['param_rok-produkcji'] = df['param_rok-produkcji'].map(lambda x: -1 ...
[08:03:36] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror. [08:03:41] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror. [08:03:45] WARNING: /workspace/src/objective/regression_obj.cu:152...
MIT
day5_hyperopt.ipynb
marta-0/dw_matrix_cars
Hyperopt
def obj_func(params): print("Training with params: ") print(params) mean_mae, score_std = run_model(xgb.XGBRegressor(**params), feats) return {'loss': np.abs(mean_mae), 'status': STATUS_OK} # space xgb_reg_params = { 'learning_rate': hp.choice('learning_rate', np.arange(0.05, 0.31, 0.05)), 'ma...
Training with params: {'colsample_bytree': 0.8, 'learning_rate': 0.25, 'max_depth': 11, 'n_estimators': 100, 'objective': 'reg:squarederror', 'seed': 0, 'subsample': 0.8500000000000001} Training with params: {'colsample_bytree': 0.9500000000000001, 'learning_rate': 0.3, 'max_depth': 11, 'n_estimators': 100, 'objectiv...
MIT
day5_hyperopt.ipynb
marta-0/dw_matrix_cars
Statistical AnalysisWe have learned null hypothesis, and compared two-sample test to check whether two samples are the same or notTo add more to statistical analysis, the follwoing topics should be covered:1- Approxite the histogram of data with combination of Gaussian (Normal) distribution functions: Gaussian Mixt...
import numpy as np import matplotlib.pyplot as plt from sklearn import mixture # Generate data samples and plot its histogram x_1 = np.random.normal(-5, 1, 3000) x_2 = np.random.normal(2, 3, 7000) x = np.concatenate((x_1, x_2)) plt.hist(x, bins=20, density=1) plt.show() # Define a GMM model and obtain its parameters...
_____no_output_____
MIT
site/public/courses/DS-1.1/Notebooks/StatisticalAnalysis.ipynb
KitsuneNoctus/makeschool
The GMM has learn the probability density function of our data sampleLets the model generate sample from it model:
z = gmm.sample(10000) plt.hist(z[0], bins=20, density=1) plt.show()
_____no_output_____
MIT
site/public/courses/DS-1.1/Notebooks/StatisticalAnalysis.ipynb
KitsuneNoctus/makeschool
Kernel Density Estimation (KDE)Kernel density estimation (KDE) is a non-parametric way to estimate the probability density function of a random variable. In other words the aim of KDE is to find probability density function (PDF) for a given dataset.Approximate the pdf of dataset:$p(x) = \frac{1}{Nh}\sum_{i = 1}^{N} \...
from sklearn.neighbors import KernelDensity kde = KernelDensity(kernel='gaussian', bandwidth=0.6) kde.fit(x.reshape(-1,1)) s = np.linspace(np.min(x), np.max(x)) log_pdf = kde.score_samples(s.reshape(-1,1)) plt.plot(s, np.exp(log_pdf)) m = kde.sample(10000) plt.hist(m, bins=20, density=1) plt.show()
_____no_output_____
MIT
site/public/courses/DS-1.1/Notebooks/StatisticalAnalysis.ipynb
KitsuneNoctus/makeschool
KDE can learn handwitten digits distribution and generate new digitshttp://scikit-learn.org/stable/auto_examples/neighbors/plot_digits_kde_sampling.html Correlation Correlation is used to test relationships between quantitative variablesSome examples of data that have a high correlation:1- Your caloric intake and you...
import pandas as pd import numpy as np import scipy.stats import seaborn as sns import scipy.stats df = pd.read_csv('Iris.csv') df = df.drop(columns=['Id', 'Species']) sns.heatmap(df.corr(), annot=True) def pearson_corr(x, y): x_mean = np.mean(x) y_mean = np.mean(y) num = [(i - x_mean)*(j - y_mean) for i,...
0.8717541573048714 (0.8717541573048712, 1.0384540627941809e-47)
MIT
site/public/courses/DS-1.1/Notebooks/StatisticalAnalysis.ipynb
KitsuneNoctus/makeschool
Helper functions for processing data and basic transforms> Functions for getting, splitting, and labeling data, as well as generic transforms Get, split, and label For most data source creation we need functions to get a list of items, split them in to train/valid sets, and label them. fastai provides functions to ma...
path = untar_data(URLs.MNIST_TINY) (path/'train').ls() # export def _get_files(p, fs, extensions=None): p = Path(p) res = [p/f for f in fs if not f.startswith('.') and ((not extensions) or f'.{f.split(".")[-1].lower()}' in extensions)] return res # export def get_files(path, extensions=None, recu...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
This is the most general way to grab a bunch of file names from disk. If you pass `extensions` (including the `.`) then returned file names are filtered by that list. Only those files directly in `path` are included, unless you pass `recurse`, in which case all child folders are also searched recursively. `folders` is ...
t3 = get_files(path/'train'/'3', extensions='.png', recurse=False) t7 = get_files(path/'train'/'7', extensions='.png', recurse=False) t = get_files(path/'train', extensions='.png', recurse=True) test_eq(len(t), len(t3)+len(t7)) test_eq(len(get_files(path/'train'/'3', extensions='.jpg', recurse=False)),0) test_eq(len(t...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
It's often useful to be able to create functions with customized behavior. `fastai.data` generally uses functions named as CamelCase verbs ending in `er` to create these functions. `FileGetter` is a simple example of such a function creator.
#export def FileGetter(suf='', extensions=None, recurse=True, folders=None): "Create `get_files` partial function that searches path suffix `suf`, only in `folders`, if specified, and passes along args" def _inner(o, extensions=extensions, recurse=recurse, folders=folders): return get_files(o/suf, exten...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
This is simply `get_files` called with a list of standard image extensions.
test_eq(len(t), len(get_image_files(path, recurse=True, folders='train'))) #export def ImageGetter(suf='', recurse=True, folders=None): "Create `get_image_files` partial function that searches path suffix `suf` and passes along `kwargs`, only in `folders`, if specified." def _inner(o, recurse=recurse, folders=f...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Same as `FileGetter`, but for image extensions.
test_eq(len(get_files(path/'train', extensions='.png', recurse=True, folders='3')), len(ImageGetter( 'train', recurse=True, folders='3')(path))) #export def get_text_files(path, recurse=True, folders=None): "Get text files in `path` recursively, only in `folders`, if specified." ret...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Split The next set of functions are used to *split* data into training and validation sets. The functions return two lists - a list of indices or masks for each of training and validation sets.
# export def RandomSplitter(valid_pct=0.2, seed=None): "Create function that splits `items` between train/val with `valid_pct` randomly." def _inner(o): if seed is not None: torch.manual_seed(seed) rand_idx = L(int(i) for i in torch.randperm(len(o))) cut = int(valid_pct * len(o)) ...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Use scikit-learn train_test_split. This allow to *split* items in a stratified fashion (uniformely according to the ‘labels‘ distribution)
# export def TrainTestSplitter(test_size=0.2, random_state=None, stratify=None, train_size=None, shuffle=True): "Split `items` into random train and test subsets using sklearn train_test_split utility." def _inner(o, **kwargs): train, valid = train_test_split(range(len(o)), test_size=test_size, random_s...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Label The final set of functions is used to *label* a single item of data.
# export def parent_label(o): "Label `item` with the parent folder name." return Path(o).parent.name
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Note that `parent_label` doesn't have anything customize, so it doesn't return a function - you can just use it directly.
test_eq(parent_label(fnames[0]), '3') test_eq(parent_label("fastai_dev/dev/data/mnist_tiny/train/3/9932.png"), '3') [parent_label(o) for o in fnames] #hide #test for MS Windows when os.path.sep is '\\' instead of '/' test_eq(parent_label(os.path.join("fastai_dev","dev","data","mnist_tiny","train", "3", "9932.png") ), '...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
`RegexLabeller` is a very flexible function since it handles any regex search of the stringified item. Pass `match=True` to use `re.match` (i.e. check only start of string), or `re.search` otherwise (default).For instance, here's an example the replicates the previous `parent_label` results.
f = RegexLabeller(fr'{os.path.sep}(\d){os.path.sep}') test_eq(f(fnames[0]), '3') [f(o) for o in fnames] f = RegexLabeller(r'(\d*)', match=True) test_eq(f(fnames[0].name), '9932') #export class ColReader(): "Read `cols` in `row` with potential `pref` and `suff`" store_attrs = 'cols' def __init__(self, cols, ...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
`cols` can be a list of column names or a list of indices (or a mix of both). If `label_delim` is passed, the result is split using it.
df = pd.DataFrame({'a': 'a b c d'.split(), 'b': ['1 2', '0', '', '1 2 3']}) f = ColReader('a', pref='0', suff='1') test_eq([f(o) for o in df.itertuples()], '0a1 0b1 0c1 0d1'.split()) f = ColReader('b', label_delim=' ') test_eq([f(o) for o in df.itertuples()], [['1', '2'], ['0'], [], ['1', '2', '3']]) df['a1'] = df['a...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Categorize -
#export class CategoryMap(CollBase): "Collection of categories with the reverse mapping in `o2i`" def __init__(self, col, sort=True, add_na=False, strict=False): if is_categorical_dtype(col): items = L(col.cat.categories, use_list=True) #Remove non-used categories while keeping o...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Multicategorize -
# export class MultiCategorize(Categorize): "Reversible transform of multi-category strings to `vocab` id" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab=None, add_na=False): super().__init__(vocab=vocab,add_na=add_na) def setups(self, dsets): if not dsets: return if...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Works in conjunction with ` MultiCategorize` or on its own if you have one-hot encoded targets (pass a `vocab` for decoding and `do_encode=False` in this case)
_tfm = OneHotEncode(c=3) test_eq(_tfm([0,2]), tensor([1.,0,1])) test_eq(_tfm.decode(tensor([0,1,1])), [1,2]) tds = Datasets([['b', 'c'], ['a'], ['a', 'c'], []], [[MultiCategorize(), OneHotEncode()]]) test_eq(tds[1], [tensor([1.,0,0])]) test_eq(tds[3], [tensor([0.,0,0])]) test_eq(tds.decode([tensor([False, True, True])]...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
End-to-end dataset example with MNIST Let's show how to use those functions to grab the mnist dataset in a `Datasets`. First we grab all the images.
path = untar_data(URLs.MNIST_TINY) items = get_image_files(path)
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Then we split between train and validation depending on the folder.
splitter = GrandparentSplitter() splits = splitter(items) train,valid = (items[i] for i in splits) train[:3],valid[:3]
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
Our inputs are images that we open and convert to tensors, our targets are labeled depending on the parent directory and are categories.
from PIL import Image def open_img(fn:Path): return Image.open(fn).copy() def img2tensor(im:Image.Image): return TensorImage(array(im)[None]) tfms = [[open_img, img2tensor], [parent_label, Categorize()]] train_ds = Datasets(train, tfms) x,y = train_ds[3] xd,yd = decode_at(train_ds,3) test_eq(parent_label(train...
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai
ToTensor -
#export class ToTensor(Transform): "Convert item to appropriate tensor class" order = 5
_____no_output_____
Apache-2.0
nbs/05_data.transforms.ipynb
Peshlex/fastai