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 |
|---|---|---|---|---|---|
Setup If you are running this generator locally(i.e. in a jupyter notebook in conda, just make sure you installed:- RDKit- DeepChem 2.5.0 & above- Tensorflow 2.4.0 & aboveThen, please skip the following part and continue from `Data Preparations`. To increase efficiency, we recommend running this molecule generator in ... | #!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
#import conda_installer
#conda_installer.install()
#!/root/miniconda/bin/conda info -e
#!pip install --pre deepchem
#import deepchem
#deepchem.__version__ | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Data PreparationsNow we are ready to import some useful functions/packages, along with our model. Import Data | import model##our model
from rdkit import Chem
from rdkit.Chem import AllChem
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import deepchem as dc | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Then, we are ready to import our dataset for training. Here, for demonstration, we'll be using this dataset of in-vitro assay that detects inhibition of SARS-CoV 3CL protease via fluorescence.The dataset is originally from [PubChem AID1706](https://pubchem.ncbi.nlm.nih.gov/bioassay/1706), previously handled by [JClinic... | df = pd.read_csv('AID1706_binarized_sars.csv') | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Observe the data above, it contains a 'smiles' column, which stands for the smiles representation of the molecules. There is also an 'activity' column, in which it is the label specifying whether that molecule is considered as hit for the protein.Here, we only need those 405 molecules considered as hits, and we'll be e... | true = df[df['activity']==1] | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Set Minimum Length for molecules Since we'll be using graphic neural network, it might be more helpful and efficient if our graph data are of the same size, thus, we'll eliminate the molecules from the training set that are shorter(i.e. lacking enough atoms) than our desired minimum size. | num_atoms = 6 #here the minimum length of molecules is 6
input_df = true['smiles']
df_length = []
for _ in input_df:
df_length.append(Chem.MolFromSmiles(_).GetNumAtoms() )
true['length'] = df_length #create a new column containing each molecule's length
true = true[true['length']>num_atoms] #Here we leave only the ... | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Now, we are ready to apply the `featurizer` function to our molecules to convert them into graphs with nodes and edges for training. | #input_df = input_df.apply(Chem.MolFromSmiles)
train_set = input_df_smiles.apply( lambda x: model.featurizer(x,max_length = num_atoms))
train_set | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
We'll take one more step to make the train_set into separate nodes and edges, which fits the format later to supply to the model for training | nodes_train, edges_train = list(zip(*train_set) ) | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Training Now, we're finally ready for generating new molecules. We'll first import some necessay functions from tensorflow. | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
The network here we'll be using is Generative Adversarial Network, as mentioned in the project introduction. Here's a great [introduction](https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/). 
gene = model.make_generator(num_atoms, noise_input_shape = 100) | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Then, with the `train_batch` function, we'll supply the necessary inputs and train our network. Upon some experimentations, an epoch of around 160 would be nice for this dataset. | generator_trained = model.train_batch(
disc, gene,
np.array(nodes_train), np.array(edges_train),
noise_input_shape = 100, EPOCH = 160, BATCHSIZE = 2,
plot_hist = True, temp_result = False
... | >0, d1=0.221, d2=0.833 g=0.681, a1=100, a2=0
>1, d1=0.054, d2=0.714 g=0.569, a1=100, a2=0
>2, d1=0.026, d2=0.725 g=0.631, a1=100, a2=0
>3, d1=0.016, d2=0.894 g=0.636, a1=100, a2=0
>4, d1=0.016, d2=0.920 g=0.612, a1=100, a2=0
>5, d1=0.012, d2=0.789 g=0.684, a1=100, a2=0
>6, d1=0.014, d2=0.733 g=0.622, a1=100, a2=0
>7, d... | MIT | example.ipynb | susanzhang233/mollykill |
There are two possible kind of failures regarding a GAN model: model collapse and failure of convergence. Model collapse would often mean that the generative part of the model wouldn't be able to generate diverse outcomes. Failure of convergence between the generative and the discriminative model could likely way be id... | no, ed = generator_trained(np.random.randint(0,20
, size =(1,100)))#generated nodes and edges
abs(no.numpy()).astype(int).reshape(num_atoms), abs(ed.numpy()).astype(int).reshape(num_atoms,num_atoms) | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
With the `de_featurizer`, we could convert the generated matrix into a smiles molecule and plot it out=) | cat, dog = model.de_featurizer(abs(no.numpy()).astype(int).reshape(num_atoms), abs(ed.numpy()).astype(int).reshape(num_atoms,num_atoms))
Chem.MolToSmiles(cat)
Chem.MolFromSmiles(Chem.MolToSmiles(cat)) | RDKit ERROR: [14:09:13] Explicit valence for atom # 1 O, 5, is greater than permitted
| MIT | example.ipynb | susanzhang233/mollykill |
Brief Result Analysis | from rdkit import DataStructs | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
With the rdkit function of comparing similarities, here we'll demonstrate a preliminary analysis of the molecule we've generated. With "CCO" molecule as a control, we could observe that the new molecule we've generated is more similar to a random selected molecule(the fourth molecule) from the initial training set.This... | DataStructs.FingerprintSimilarity(Chem.RDKFingerprint(Chem.MolFromSmiles("[Li]NBBC=N")), Chem.RDKFingerprint(Chem.MolFromSmiles("CCO")))# compare with the control
#compare with one from the original data
DataStructs.FingerprintSimilarity(Chem.RDKFingerprint(Chem.MolFromSmiles("[Li]NBBC=N")), Chem.RDKFingerprint(Chem.Mo... | _____no_output_____ | MIT | example.ipynb | susanzhang233/mollykill |
Large DataFrame Tests - NYC CAB | BASE_DIR = '/mnt/roscoe/data/fuzzydata/fuzzydatatest/nyc-cab/'
frameworks = ['pandas', 'sqlite', 'modin_dask', 'modin_ray']
all_perfs = []
for f in frameworks:
result_file = glob.glob(f"{BASE_DIR}/{f}/*_perf.csv")[0]
perf_df = pd.read_csv(result_file, index_col=0)
perf_df['end_time_seconds'] = np.cumsum(pe... | _____no_output_____ | MIT | examples/Result_Analysis.ipynb | suhailrehman/fuzzydata |
Combined Performance / Scaling Graph | BASE_DIR = '/mnt/roscoe/data/fuzzydata/fuzzydata_scaling_test_3/'
frameworks = ['pandas', 'sqlite', 'modin_dask', 'modin_ray']
sizes = ['1000', '10000', '100000', '1000000', '5000000']
all_perfs = []
for framework in frameworks:
for size in sizes:
input_dir = f"{BASE_DIR}/{framework}_{size}/"
try:... | _____no_output_____ | MIT | examples/Result_Analysis.ipynb | suhailrehman/fuzzydata |
DataMining TwitterAPIRequirements:- TwitterAccount- TwitterApp credentials ImportsThe following imports are requiered to mine data from Twitter | # http://tweepy.readthedocs.io/en/v3.5.0/index.html
import tweepy
# https://api.mongodb.com/python/current/
import pymongo
import json
import sys | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Access and Test the TwitterAPIInsert your `CONSUMER_KEY`, `CONSUMER_SECRET`, `ACCESS_TOKEN` and `ACCESS_TOKEN_SECRET` and run the code snippet to test if access is granted. If everything works well 'tweepy...' will be posted to your timeline. | # Set the received credentials for your recently created TwitterAPI
CONSUMER_KEY = 'MmiELrtF7fSp3vptCID8jKril'
CONSUMER_SECRET = 'HqtMRk4jpt30uwDOLz30jHqZm6TPN6rj3oHFaL6xFxw2k0GkDC'
ACCESS_TOKEN = '116725830-rkT63AILxR4fpf4kUXd8xJoOcHTsGkKUOKSMpMJQ'
ACCESS_TOKEN_SECRET = 'eKzxfku4GdYu1wWcMr5iusTmhFT35cDWezMU2Olr5UD4i'
... | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
mongoDBTo gain access to the mongoDB the library `pymongo` is used.In the first step the mongoDB URL is defined. | MONGO_URL = 'mongodb://twitter-mongodb:27017/' | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Next, two functions are defined to save and load data from mongoDB. | def save_to_mongo(data, mongo_db, mongo_db_coll):
# Connects to the MongoDB server running on
client = pymongo.MongoClient(MONGO_URL)
# Get a reference to a particular database
db = client[mongo_db]
# Reference a particular collection in the database
coll = db[mongo_db_coll]
# Perform a bulk... | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Stream tweets to mongoDBNow we want to stream tweets to a current trend to the mongoDB.Therefore we ask the TwitterAPI for current Trends within different places. Places are defined with WOEID https://www.flickr.com/places/info/1 | # WORLD
print('trends WORLD')
trends = twitter.trends_place(1)[0]['trends']
for t in trends[:5]:
print(json.dumps(t['name'],indent=1))
# US
print('\ntrends US')
trends = twitter.trends_place(23424977)[0]['trends']
for t in trends[:5]:
print(json.dumps(t['name'],indent=1))
# AT
print('\ntrends AUSTRIA')
trends =... | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
StreamListenertweepy provides a StreamListener that allows to stream live tweets. All streamed tweets are stored to the mongoDB. | MONGO_DB = 'trends'
MONGO_COLL = 'tweets'
TREND = '#BestBoyBand'
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, twitter):
self.twitter = twitter
super(tweepy.StreamListener, self).__init__()
self.db = pymongo.MongoClient(MONGO_URL)[MONGO_DB]
self.number = 1
... | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Collect tweets from a specific userIn this use-case we mine data from a specific user. | MONGO_DB = 'trump'
MONGO_COLL = 'tweets'
TWITTER_USER = '@realDonaldTrump'
def get_all_tweets(screen_name):
#initialize a list to hold all the tweepy Tweets
alltweets = []
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = twitter.user_timeline(screen_name... | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Load tweets from mongo | data = load_from_mongo('trends', 'tweets')
for d in data[:5]:
print(d['text']) | _____no_output_____ | MIT | jupyter-notebooks/02_DataMining_TwitterAPI.ipynb | amarbajric/INDBA-ML |
Graphs from the presentation | import matplotlib.pyplot as plt
%matplotlib notebook
# create a new figure
plt.figure()
# create x and y coordinates via lists
x = [99, 19, 88, 12, 95, 47, 81, 64, 83, 76]
y = [43, 18, 11, 4, 78, 47, 77, 70, 21, 24]
# scatter the points onto the figure
plt.scatter(x, y)
# create a new figure
plt.figure()
# create ... | _____no_output_____ | MIT | 6. Advanced Visualisation Tools/Graphs from the presentation.ipynb | nickelnine37/VisualAnalyticsWithPython |
SOLUCION 1 | h1 = 0
h2 = 0
m1 = 0
m2 = 0 # 1440 + 24 *6
contador = 0 # 5 + (1440 + ?) * 2 + 144 + 24 + 2= 3057
while [h1, h2, m1, m2] != [2,3,5,9]:
if [h1, h2] == [m2, m1]:
print(h1, h2,":", m1, m2)
m2 = m2 + 1
if m2 == 10:
m2 = 0
m1 = m1 + 1
if m1 == 6:
h2 = h2 + 1
m2 = 0
... | _____no_output_____ | MIT | 28Octubre.ipynb | VxctxrTL/daa_2021_1 |
Solucion 2 | horario="0000"
contador=0
while horario!="2359":
inv=horario[::-1]
if horario==inv:
contador+=1
print(horario[0:2],":",horario[2:4])
new=int(horario)
new+=1
horario=str(new).zfill(4)
print("son ",contador,"palindromos")
# 2 + (2360 * 4 ) + 24 | _____no_output_____ | MIT | 28Octubre.ipynb | VxctxrTL/daa_2021_1 |
Solucion 3 | lista=[]
for i in range(0,24,1): # 24
for j in range(0,60,1): # 60 1440
if i<10:
if j<10:
lista.append("0"+str(i)+":"+"0"+str(j))
elif j>=10:
lista.append("0"+str(i)+":"+str(j))
else:
if i>=10:
if j<10:
lista.append(str(i)+":"+"0"+str(j))
elif j... | _____no_output_____ | MIT | 28Octubre.ipynb | VxctxrTL/daa_2021_1 |
Getting ready | import tensorflow as tf
import tensorflow.keras as keras
import pandas as pd
import numpy as np
census_dir = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/'
train_path = tf.keras.utils.get_file('adult.data', census_dir + 'adult.data')
test_path = tf.keras.utils.get_file('adult.test', census_dir + 'ad... | _____no_output_____ | MIT | Chapter 4 - Linear Regression/Using Wide & Deep models.ipynb | Young-Picasso/TensorFlow2.x_Cookbook |
How to do it | predictors = ['age', 'workclass', 'education', 'education_num', 'marital_status', 'occupation', 'relationship',
'gender']
y_train = (train_data.income_bracket==' >50K').astype(int)
y_test = (test_data.income_bracket==' >50K').astype(int)
train_data = train_data[predictors]
test_data = test_data[predictor... | INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tmpxnk3fqlo/model.ckpt-1500
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
| MIT | Chapter 4 - Linear Regression/Using Wide & Deep models.ipynb | Young-Picasso/TensorFlow2.x_Cookbook |
Automated Machine Learning Forecasting away from training data Contents1. [Introduction](Introduction)2. [Setup](Setup)3. [Data](Data)4. [Prepare remote compute and data.](prepare_remote)4. [Create the configuration and train a forecaster](train)5. [Forecasting from the trained model](forecasting)6. [Forecasting away ... | import os
import pandas as pd
import numpy as np
import logging
import warnings
import azureml.core
from azureml.core.dataset import Dataset
from pandas.tseries.frequencies import to_offset
from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget
from azureml.core.runconfig import Run... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
This sample notebook may use features that are not available in previous versions of the Azure ML SDK. | print("This notebook was created using version 1.8.0 of the Azure ML SDK")
print("You are currently using version", azureml.core.VERSION, "of the Azure ML SDK")
from azureml.core.workspace import Workspace
from azureml.core.experiment import Experiment
from azureml.train.automl import AutoMLConfig
ws = Workspace.from_... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
DataFor the demonstration purposes we will generate the data artificially and use them for the forecasting. | TIME_COLUMN_NAME = 'date'
GRAIN_COLUMN_NAME = 'grain'
TARGET_COLUMN_NAME = 'y'
def get_timeseries(train_len: int,
test_len: int,
time_column_name: str,
target_column_name: str,
grain_column_name: str,
grains: int = 1,
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Let's see what the training data looks like. | X_train.tail()
# plot the example time series
import matplotlib.pyplot as plt
whole_data = X_train.copy()
target_label = 'y'
whole_data[target_label] = y_train
for g in whole_data.groupby('grain'):
plt.plot(g[1]['date'].values, g[1]['y'].values, label=g[0])
plt.legend()
plt.show() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Prepare remote compute and data. The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace), is paired with the storage account, which contains the default data store. We will use it to upload the artificial data and create [tabular dataset](https://docs... | # We need to save thw artificial data and then upload them to default workspace datastore.
DATA_PATH = "fc_fn_data"
DATA_PATH_X = "{}/data_train.csv".format(DATA_PATH)
if not os.path.isdir('data'):
os.mkdir('data')
pd.DataFrame(whole_data).to_csv("data/data_train.csv", index=False)
# Upload saved data to the defaul... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targetsamlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource. | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# Choose a name for your CPU cluster
amlcompute_cluster_name = "fcfn-cluster"
# Verify that cluster does not exist already
try:
compute_target = ComputeTarget(workspace=ws, name=amlcompute_clu... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Create the configuration and train a forecaster First generate the configuration, in which we:* Set metadata columns: target, time column and grain column names.* Validate our data using cross validation with rolling window method.* Set normalized root mean squared error as a metric to select the best model.* Set earl... | lags = [1,2,3]
max_horizon = n_test_periods
time_series_settings = {
'time_column_name': TIME_COLUMN_NAME,
'grain_column_names': [ GRAIN_COLUMN_NAME ],
'max_horizon': max_horizon,
'target_lags': lags
} | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Run the model selection and training process. | from azureml.core.workspace import Workspace
from azureml.core.experiment import Experiment
from azureml.train.automl import AutoMLConfig
automl_config = AutoMLConfig(task='forecasting',
debug_log='automl_forecasting_function.log',
primary_metric='normalized_r... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Forecasting from the trained model In this section we will review the `forecast` interface for two main scenarios: forecasting right after the training data, and the more complex interface for forecasting when there is a gap (in the time sense) between training and testing data. X_train is directly followed by the X... | # The data set contains hourly data, the training set ends at 01/02/2000 at 05:00
# These are predictions we are asking the model to make (does not contain thet target column y),
# for 6 periods beginning with 2000-01-02 06:00, which immediately follows the training data
X_test
y_pred_no_gap, xy_nogap = fitted_model.... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Confidence intervals Forecasting model may be used for the prediction of forecasting intervals by running ```forecast_quantiles()```. This method accepts the same parameters as forecast(). | quantiles = fitted_model.forecast_quantiles(X_test)
quantiles | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Distribution forecastsOften the figure of interest is not just the point prediction, but the prediction at some quantile of the distribution. This arises when the forecast is used to control some kind of inventory, for example of grocery items or virtual machines for a cloud service. In such case, the control point is... | # specify which quantiles you would like
fitted_model.quantiles = [0.01, 0.5, 0.95]
# use forecast_quantiles function, not the forecast() one
y_pred_quantiles = fitted_model.forecast_quantiles(X_test)
# quantile forecasts returned in a Dataframe along with the time and grain columns
y_pred_quantiles | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Destination-date forecast: "just do something"In some scenarios, the X_test is not known. The forecast is likely to be weak, because it is missing contemporaneous predictors, which we will need to impute. If you still wish to predict forward under the assumption that the last known values will be carried forward, you ... | # We will take the destination date as a last date in the test set.
dest = max(X_test[TIME_COLUMN_NAME])
y_pred_dest, xy_dest = fitted_model.forecast(forecast_destination=dest)
# This form also shows how we imputed the predictors which were not given. (Not so well! Use with caution!)
xy_dest | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Forecasting away from training data Suppose we trained a model, some time passed, and now we want to apply the model without re-training. If the model "looks back" -- uses previous values of the target -- then we somehow need to provide those values to the model. Using only `X_away` will fail without adding context data for the model to consume. | try:
y_pred_away, xy_away = fitted_model.forecast(X_away)
xy_away
except Exception as e:
print(e) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
How should we read that eror message? The forecast origin is at the last time the model saw an actual value of `y` (the target). That was at the end of the training data! The model is attempting to forecast from the end of training data. But the requested forecast periods are past the maximum horizon. We need to provid... | def make_forecasting_query(fulldata, time_column_name, target_column_name, forecast_origin, horizon, lookback):
"""
This function will take the full dataset, and create the query
to predict all values of the grain from the `forecast_origin`
forward for the next `horizon` horizons. Context from previous... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Let's see where the context data ends - it ends, by construction, just before the testing data starts. | print(X_context.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))
print(X_away.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))
X_context.tail(5)
# Since the length of the lookback is 3,
# we need to add 3 periods from the context to the request
# so that the model has th... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Note that the forecast origin is at 17:00 for both grains, and periods from 18:00 are to be forecast. | # Now everything works
y_pred_away, xy_away = fitted_model.forecast(X_pred, y_pred)
# show the forecast aligned
X_show = xy_away.reset_index()
# without the generated features
X_show[['date', 'grain', 'ext_predictor', '_automl_target_col']]
# prediction is in _automl_target_col | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Forecasting farther than the maximum horizon When the forecast destination, or the latest date in the prediction data frame, is farther into the future than the specified maximum horizon, the `forecast()` function will still make point predictions out to the later date using a recursive operation mode. Internally, the... | # generate the same kind of test data we trained on, but with a single grain/time-series and test period twice as long as the max_horizon
_, _, X_test_long, y_test_long = get_timeseries(train_len=n_train_periods,
test_len=max_horizon*2,
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
Confidence interval and distributional forecastsAutoML cannot currently estimate forecast errors beyond the maximum horizon set during training, so the `forecast_quantiles()` function will return missing values for quantiles not equal to 0.5 beyond the maximum horizon. | fitted_model.forecast_quantiles(X_test_long) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb | hyoshioka0128/MachineLearningNotebooks |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
path =("https://raw.githubusercontent.com/18cse005/DMDW/main/USA_cars_datasets.csv")
data=pd.read_csv(path)
type(data)
data.info
data.shape
data.index
data.columns
data.head()
data.tail()
data.head(10)
data.isnull().sum()
data.dropna(inplace=True) #... | _____no_output_____ | Apache-2.0 | Data_preprocessing.ipynb | 18cse081/dmdw | |
Introduction and Foundations: Titanic Survival Exploration> Udacity Machine Learning Engineer Nanodegree: _Project 0_>> Author: _Ke Zhang_>> Submission Date: _2017-04-27_ (Revision 2) AbstractIn 1912, the ship RMS Titanic struck an iceberg on its maiden voyage and sank, resulting in the deaths of most of its passenge... | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the dataset
in_file... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship:- **Survived**: Outcome of survival (0 = No; 1 = Yes)- **Pclass**: Socio-economic class (1 = Upper class; 2 = Middle class; 3 = Lower class)- **Name**: Name of passenger- **Sex**: Sex of the passenger- **Age**:... | # Store the 'Survived' feature in a new variable and remove it from the dataset
outcomes = full_data['Survived']
data = full_data.drop('Survived', axis = 1)
# Show the new dataset with 'Survived' removed
display(data.head()) | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
The very same sample of the RMS Titanic data now shows the **Survived** feature removed from the DataFrame. Note that `data` (the passenger data) and `outcomes` (the outcomes of survival) are now *paired*. That means for any passenger `data.loc[i]`, they have the survival outcome `outcomes[i]`.To measure the performanc... | def accuracy_score(truth, pred):
""" Returns accuracy score for input truth and predictions. """
# Ensure that the number of predictions matches number of outcomes
if len(truth) == len(pred):
# Calculate and return the accuracy as a percent
return "Predictions have an accuracy... | Predictions have an accuracy of 60.00%.
| Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
> **Tip:** If you save an iPython Notebook, the output from running code blocks will also be saved. However, the state of your workspace will be reset once a new session is started. Make sure that you run all of the code blocks from your previous session to reestablish variables and functions before picking up where yo... | def predictions_0(data):
""" Model with no features. Always predicts a passenger did not survive. """
predictions = []
for _, passenger in data.iterrows():
# Predict the survival of 'passenger'
predictions.append(0)
# Return our predictions
return pd.Series(predictions... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Question 1*Using the RMS Titanic data, how accurate would a prediction be that none of the passengers survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 61.62%.
| Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
**Answer:** The prediction accuracy is **61.62%** ***Let's take a look at whether the feature **Sex** has any indication of survival rates among passengers using the `survival_stats` function. This function is defined in the `titanic_visualizations.py` Python script included with this project. The first two parameters ... | vs.survival_stats(data, outcomes, 'Sex') | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Examining the survival statistics, a large majority of males did not survive the ship sinking. However, a majority of females *did* survive the ship sinking. Let's build on our previous prediction: If a passenger was female, then we will predict that they survived. Otherwise, we will predict the passenger did not survi... | def predictions_1(data):
""" Model with one feature:
- Predict a passenger survived if they are female. """
predictions = []
for _, passenger in data.iterrows():
predictions.append(True if passenger['Sex'] == 'female'
else False)
# Return our pr... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Question 2*How accurate would a prediction be that all female passengers survived and the remaining passengers did not survive?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 78.68%.
| Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
**Answer**: **78.68**% ***Using just the **Sex** feature for each passenger, we are able to increase the accuracy of our predictions by a significant margin. Now, let's consider using an additional feature to see if we can further improve our predictions. For example, consider all of the male passengers aboard the RMS ... | vs.survival_stats(data, outcomes, 'Age', ["Sex == 'male'"]) | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Examining the survival statistics, the majority of males younger than 10 survived the ship sinking, whereas most males age 10 or older *did not survive* the ship sinking. Let's continue to build on our previous prediction: If a passenger was female, then we will predict they survive. If a passenger was male and younger... | def predictions_2(data):
""" Model with two features:
- Predict a passenger survived if they are female.
- Predict a passenger survived if they are male and younger than 10. """
predictions = []
for _, passenger in data.iterrows():
predictions.append(True if passenger['... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Question 3*How accurate would a prediction be that all female passengers and all male passengers younger than 10 survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 79.35%.
| Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
**Answer**: **79.35** ***Adding the feature **Age** as a condition in conjunction with **Sex** improves the accuracy by a small margin more than with simply using the feature **Sex** alone. Now it's your turn: Find a series of features and conditions to split the data on to obtain an outcome prediction accuracy of at l... | # survival by Embarked
vs.survival_stats(data, outcomes, 'Embarked')
# survival by Embarked
vs.survival_stats(data, outcomes, 'SibSp')
vs.survival_stats(data, outcomes, 'Age', ["Sex == 'male'", "Age < 18"]) | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
We found out earlier that female and children had better chance to survive. In the next step we'll add another criteria 'Pclass' to further distinguish the survival rates among the different groups. | # female passengers in the higher pclass had great chance to survive
vs.survival_stats(data, outcomes, 'Pclass', [
"Sex == 'female'"
])
# male passengers in the higher pclass had great chance to survive
vs.survival_stats(data, outcomes, 'Pclass', [
"Sex == 'male'"
])
# more female passengers survived in all age... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
It looks like that all female passengers under 20 survived from the accident. Let's check passengers in the lower class to complete our guess. | # ... but not in the lower class when they're older than 20
vs.survival_stats(data, outcomes, 'Age', [
"Sex == 'female'",
"Pclass == 3"
])
# ... actually only females under 20 had more survivers in the lower class
vs.survival_stats(data, outcomes, 'Age', [
"Sex == 'male'",
"Pclass == 3"
]) | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
> We conclude that in the lower class only female under 20 had better chance to survive. In the other classes all children under 10 and female passengers had more likey survived. Let's check if we have reached our 80% target. After exploring the survival statistics visualization, fill in the missing code below so that ... | def predictions_3(data):
"""
Model with multiple features: Sex, Age and Pclass
Makes a prediction with an accuracy of at least 80%.
"""
predictions = []
for _, passenger in data.iterrows():
if passenger['Age'] < 10:
survived = True
elif passenger['Sex'] == 'fem... | _____no_output_____ | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Question 4*Describe the steps you took to implement the final prediction model so that it got an accuracy of at least 80%. What features did you look at? Were certain features more informative than others? Which conditions did you use to split the survival outcomes in the data? How accurate are your predictions?* **H... | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 80.36%.
| Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
**Answer**: Using the features *Sex*, *Pclass* and *Age* we increased the accuracy score to **80.36%**.We tried to plot the survival statistics with different features and chose the ones under which conditions the differences were the largest.* some features are just not relevant like *PassengerId* or *Name** some feat... | import IPython
print IPython.sys_info()
!pip freeze | alabaster==0.7.9
anaconda-client==1.6.0
anaconda-navigator==1.4.3
argcomplete==1.0.0
astroid==1.4.9
astropy==1.3
Babel==2.3.4
backports-abc==0.5
backports.shutil-get-terminal-size==1.0.0
backports.ssl-match-hostname==3.4.0.2
beautifulsoup4==4.5.3
bitarray==0.8.1
blaze==0.10.1
bokeh==0.12.4
boto==2.45.0
Bottleneck==1.2.... | Apache-2.0 | p0_ss_titanic_survival_exploration/p0_ss_titanic_survival_exploration.ipynb | superkley/udacity-mlnd |
Preclustering and Cluster Enriched Features PurposeThe purpose of this step is to perform a simple pre-clustering using the highly variable features to get a pre-clusters labeling. We then select top enriched features for each cluster (CEF) for further analysis. Input- HVF adata file. Output- HVF adata file with pre-c... | import seaborn as sns
import anndata
import scanpy as sc
from ALLCools.clustering import cluster_enriched_features, significant_pc_test, log_scale
sns.set_context(context='notebook', font_scale=1.3) | _____no_output_____ | MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Parameters | adata_path = 'mCH.HVF.h5ad'
# Cluster Enriched Features analysis
top_n=200
alpha=0.05
stat_plot=True
# you may provide a pre calculated cluster version.
# If None, will perform basic clustering using parameters below.
cluster_col = None
# These parameters only used when cluster_col is None
k=25
resolution=1
clust... | _____no_output_____ | MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Load Data | adata = anndata.read_h5ad(adata_path) | _____no_output_____ | MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Pre-ClusteringIf cluster label is not provided, will perform basic clustering here | if cluster_col is None:
# IMPORTANT
# put the unscaled matrix in adata.raw
adata.raw = adata
log_scale(adata)
sc.tl.pca(adata, n_comps=100)
significant_pc_test(adata, p_cutoff=0.1, update=True)
sc.pp.neighbors(adata, n_neighbors=k)
sc.tl.leiden(adata, resolution=resolution)
... | 32 components passed P cutoff of 0.1.
Changing adata.obsm['X_pca'] from shape (16985, 100) to (16985, 32)
| MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Cluster Enriched Features (CEF) | cluster_enriched_features(adata,
cluster_col=cluster_col,
top_n=top_n,
alpha=alpha,
stat_plot=True) | Found 31 clusters to compute feature enrichment score
Computing enrichment score
Computing enrichment score FDR-corrected P values
Selected 3102 unique features
| MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Save AnnData | # save adata
adata.write_h5ad(adata_path)
adata | _____no_output_____ | MIT | docs/allcools/cell_level/step_by_step/100kb/04a-PreclusteringAndClusterEnrichedFeatures-mCH.ipynb | mukamel-lab/ALLCools |
Ploting Different Polling Methods | pollster_rating = pd.read_csv("pollster-ratings.csv")
Methodologies_frequencies = pollster_rating.Methodology.value_counts()
plt.bar(Methodologies_frequencies.index, Methodologies_frequencies)
plt.xticks(rotation = "vertical")
plt.title("Methodolgies of Diffrent Pollsters")
plt.ylabel("Number of Pollsters")
plt.xlabel(... | _____no_output_____ | CC-BY-4.0 | pollster-ratings/Visualization.ipynb | machinglearnin/data |
Plotting Poll Size Distribution | plt.figure(figsize = (10,6))
plt.hist(pollster_rating['# of Polls'])
plt.title("Distrubution of Polling Sizes Among Diffrent Pollsters")
plt.xlabel("# of Polls Conducted")
plt.show() | _____no_output_____ | CC-BY-4.0 | pollster-ratings/Visualization.ipynb | machinglearnin/data |
Accuracy of Pollsters | #selects only Pollsters with 100+ Polls
frequent_pollsters = pollster_rating[pollster_rating['# of Polls'] > 100]
frequent_pollsters = frequent_pollsters.set_index('Pollster')
#Reformats Races Called Correclty Data so it ban be sorted
Races_called_correctly = frequent_pollsters['Races Called Correctly'].str.rstrip('%'... | _____no_output_____ | CC-BY-4.0 | pollster-ratings/Visualization.ipynb | machinglearnin/data |
Are More Frequent Pollsters More Accurate? | pollster_above_10 = pollster_rating[pollster_rating['# of Polls'] > 100]
plt.figure(figsize = (8,6))
x_list = pollster_above_10['# of Polls']
y_list = pollster_above_10['Races Called Correctly'].str.rstrip('%').astype(int)
plt.scatter(x_list, y_list)
plt.yticks(np.arange(0, 110, 10))
plt.title("Comparison of Pollsters ... | _____no_output_____ | CC-BY-4.0 | pollster-ratings/Visualization.ipynb | machinglearnin/data |
Before you begin1. Use the [Cloud Resource Manager](https://console.cloud.google.com/cloud-resource-manager) to Create a Cloud Platform project if you do not already have one.2. [Enable billing](https://support.google.com/cloud/answer/6293499enable-billing) for the project.3. [Enable BigQuery](https://console.c... | from google.colab import auth
auth.authenticate_user()
print('Authenticated') | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Optional: Enable data table displayColab includes the ``google.colab.data_table`` package that can be used to display large pandas dataframes as an interactive data table.It can be enabled with: | %load_ext google.colab.data_table | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
If you would prefer to return to the classic Pandas dataframe display, you can disable this by running:```python%unload_ext google.colab.data_table``` Use BigQuery via magicsThe `google.cloud.bigquery` library also includes a magic command which runs a query and either displays the result or saves it to a variable as ... | # Display query output immediately
%%bigquery --project yourprojectid
SELECT
COUNT(*) as total_rows
FROM `bigquery-public-data.samples.gsod`
# Save output in a variable `df`
%%bigquery --project yourprojectid df
SELECT
COUNT(*) as total_rows
FROM `bigquery-public-data.samples.gsod`
df | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Use BigQuery through google-cloud-bigquerySee [BigQuery documentation](https://cloud.google.com/bigquery/docs) and [library reference documentation](https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html).The [GSOD sample table](https://bigquery.cloud.google.com/table/bigquery-public-data... | project_id = '[your project ID]' | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Sample approximately 2000 random rows | from google.cloud import bigquery
client = bigquery.Client(project=project_id)
sample_count = 2000
row_count = client.query('''
SELECT
COUNT(*) as total
FROM `bigquery-public-data.samples.gsod`''').to_dataframe().total[0]
df = client.query('''
SELECT
*
FROM
`bigquery-public-data.samples.gsod`
... | Full dataset has 114420316 rows
| MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Describe the sampled data | df.describe() | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
View the first 10 rows | df.head(10)
# 10 highest total_precipitation samples
df.sort_values('total_precipitation', ascending=False).head(10)[['station_number', 'year', 'month', 'day', 'total_precipitation']] | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Use BigQuery through pandas-gbqThe `pandas-gbq` library is a community led project by the pandas community. It covers basic functionality, such as writing a DataFrame to BigQuery and running a query, but as a third-party library it may not handle all BigQuery features or use cases.[Pandas GBQ Documentation](https://pa... | import pandas as pd
sample_count = 2000
df = pd.io.gbq.read_gbq('''
SELECT name, SUM(number) as count
FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE state = 'TX'
GROUP BY name
ORDER BY count DESC
LIMIT 100
''', project_id=project_id, dialect='standard')
df.head() | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Syntax highlighting`google.colab.syntax` can be used to add syntax highlighting to any Python string literals which are used in a query later. | from google.colab import syntax
query = syntax.sql('''
SELECT
COUNT(*) as total_rows
FROM
`bigquery-public-data.samples.gsod`
''')
pd.io.gbq.read_gbq(query, project_id=project_id, dialect='standard') | _____no_output_____ | MIT | Getting_started_with_BigQuery.ipynb | darshanbk/100-Days-Of-ML-Code |
Solving Multi-armed Bandit Problems We will focus on how to solve the multi-armed bandit problem using four strategies, including epsilon-greedy, softmax exploration, upper confidence bound, and Thompson sampling. We will see how they deal with the exploration-exploitation dilemma in their own unique ways. We will als... | import torch
class BanditEnv():
"""
Multi-armed bandit environment
payout_list:
A list of probabilities of the likelihood that a particular bandit will pay out
reward_list:
A list of rewards of the payout that bandit has
"""
def __init__(self, payout_list, reward_list):
... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
In the example we just worked on, there are three slot machines. Each machine has a different payout (reward) and payout probability. In each episode, we randomly chose one arm of the machine to pull (one action to execute) and get a payout at a certain probability. Arm 1 is the best arm with the largest average reward... | import torch
bandit_payout = [0.1, 0.15, 0.3]
bandit_reward = [4, 3, 1]
bandit_env = BanditEnv(bandit_payout, bandit_reward)
n_episode = 100000
n_action = len(bandit_payout)
action_count = [0 for _ in range(n_action)]
action_total_reward = [0 for _ in range(n_action)]
action_avg_reward = [[] for action in range(n_act... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Arm 1 is the best arm, with the largest average reward at the end. Also, its average reward starts to saturate after around 1,000 episodes. You may wonder whether the epsilon-greedy policy actually outperforms the random policy. Besides the fact that the value for the optimal arm converges earlier with the epsilon-gree... | print(sum(action_total_reward) / n_episode) | 0.43616
| Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Over 100,000 episodes, the average payout is 0.43718 with the epsilon-greedy policy. Repeating the same computation for the random policy solution, we get 0.37902 as the average payout. Solving multi-armed bandit problems with the softmax explorationAs we've seen with epsilon-greedy, when performing exploration we ran... | import torch
bandit_payout = [0.1, 0.15, 0.3]
bandit_reward = [4, 3, 1]
bandit_env = BanditEnv(bandit_payout, bandit_reward)
n_episode = 100000
n_action = len(bandit_payout)
action_count = [0 for _ in range(n_action)]
action_total_reward = [0 for _ in range(n_action)]
action_avg_reward = [[] for action in range(n_act... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Arm 1 is the best arm, with the largest average reward at the end. Also, its average reward starts to saturate after around 800 episodes in this example. Solving multi-armed bandit problems with the upper confidence bound algorithmIn the previous two recipes, we explored random actions in the multi-armed bandit proble... | import torch
bandit_payout = [0.1, 0.15, 0.3]
bandit_reward = [4, 3, 1]
bandit_env = BanditEnv(bandit_payout, bandit_reward)
n_episode = 100000
n_action = len(bandit_payout)
action_count = torch.tensor([0. for _ in range(n_action)])
action_total_reward = [0 for _ in range(n_action)]
action_avg_reward = [[] for action... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Arm 1 is the best arm, with the largest average reward in the end. You may wonder whether UCB actually outperforms the epsilon-greedy policy. We can compute the average reward over the entire training process, and the policy with the highest average reward learns faster.We can simply average the reward over all episode... | print(sum(action_total_reward) / n_episode) | 0.4433
| Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Over 100,000 episodes, the average payout is 0.44605 with UCB, which is higher than 0.43718 with the epsilon-greedy policy. Solving internet advertising problems with a multi-armed banditImagine you are an advertiser working on ad optimization on a website:- There are three different colors of ad background – red, gre... | import torch
bandit_payout = [0.01, 0.015, 0.03]
bandit_reward = [1, 1, 1]
bandit_env = BanditEnv(bandit_payout, bandit_reward)
n_episode = 100000
n_action = len(bandit_payout)
action_count = torch.tensor([0. for _ in range(n_action)])
action_total_reward = [0 for _ in range(n_action)]
action_avg_reward = [[] for act... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Ad 2 is the best ad with the highest predicted CTR (average reward) after the model converges.Eventually, we found that ad 2 is the optimal one to choose, which is true. Also, the sooner we figure this out the better, because we will lose fewer potential clicks. In this example, ad 2 outperformed the others after aroun... | import torch
import matplotlib.pyplot as plt
beta1 = torch.distributions.beta.Beta(1, 1)
samples1 = [beta1.sample() for _ in range(100000)]
plt.hist(samples1, range=[0, 1], bins=10)
plt.title('beta(1, 1)')
plt.show()
beta2 = torch.distributions.beta.Beta(5, 1)
samples2 = [beta2.sample() for _ in range(100000)]
plt.hist... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
In this recipe, we solved the ad bandits problem with the TS algorithm. The biggest difference between TS and the three other approaches is the adoption of Bayesian optimization. It first computes the prior distribution for each possible arm, and then randomly draws a value from each distribution. It then picks the arm... | def thompson_sampling(alpha, beta):
prior_values = torch.distributions.beta.Beta(alpha, beta).sample()
return torch.argmax(prior_values)
alpha = torch.ones(n_action)
beta = torch.ones(n_action)
for episode in range(n_episode):
action = thompson_sampling(alpha, beta)
reward = bandit_env.step(action)
... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Ad 2 is the best ad, with the highest predicted CTR (average reward). Solving internet advertising problems with contextual banditsYou may notice that in the ad optimization problem, we only care about the ad and ignore other information, such as user information and web page information, that might affect the ad bein... | import torch
bandit_payout_machines = [
[0.01, 0.015, 0.03],
[0.025, 0.01, 0.015]
]
bandit_reward_machines = [
[1, 1, 1],
[1, 1, 1]
]
n_machine = len(bandit_payout_machines)
bandit_env_machines = [BanditEnv(bandit_payout, bandit_reward)
for bandit_payout, bandit_reward in
... | _____no_output_____ | Apache-2.0 | _notebooks/2022-01-20-mab.ipynb | recohut/notebook |
Copyright 2018 The TensorFlow Authors. | #@title 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
不规则张量 在 TensorFlow.org 上查看 在 Google Colab 中运行 在 Github 上查看源代码 {img}下载笔记本 **API 文档:** [`tf.RaggedTensor`](https://tensorflow.google.cn/api_docs/python/tf/RaggedTensor) [`tf.ragged`](https://tensorflow.google.cn/api_docs/python/tf/ragged) 设置 | !pip install -q tf_nightly
import math
import tensorflow as tf | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
概述数据有多种形状;张量也应当有多种形状。*不规则张量*是嵌套的可变长度列表的 TensorFlow 等效项。它们使存储和处理包含非均匀形状的数据变得容易,包括:- 可变长度特征,例如电影的演员名单。- 成批的可变长度顺序输入,例如句子或视频剪辑。- 分层输入,例如细分为节、段落、句子和单词的文本文档。- 结构化输入中的各个字段,例如协议缓冲区。 不规则张量的功能有一百多种 TensorFlow 运算支持不规则张量,包括数学运算(如 `tf.add` 和 `tf.reduce_mean`)、数组运算(如 `tf.concat` 和 `tf.tile`)、字符串操作运算(如 `tf.substr`)、控制流运算(如 `tf.whi... | digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
words = tf.ragged.constant([["So", "long"], ["thanks", "for", "all", "the", "fish"]])
print(tf.add(digits, 3))
print(tf.reduce_mean(digits, axis=1))
print(tf.concat([digits, [[5, 3]]], axis=0))
print(tf.tile(digits, [1, 2]))
print(tf.strings.substr(wor... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
还有专门针对不规则张量的方法和运算,包括工厂方法、转换方法和值映射运算。有关支持的运算列表,请参阅 **`tf.ragged` 包文档**。 许多 TensorFlow API 都支持不规则张量,包括 [Keras](https://tensorflow.google.cn/guide/keras)、[Dataset](https://tensorflow.google.cn/guide/data)、[tf.function](https://tensorflow.google.cn/guide/function)、[SavedModel](https://tensorflow.google.cn/guide/saved_model... | print(digits[0]) # First row
print(digits[:, :2]) # First two values in each row.
print(digits[:, -2:]) # Last two values in each row. | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.