markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
When the query is complete, the results appear below the query. The
results should look like the following. Because model training is not
deterministic, your results may differ.
In the next example, you try to predict the number of transactions each website
visitor will make. This query is identical to the previous qu... | %%bigquery
SELECT
fullVisitorId,
SUM(predicted_label) as total_predicted_purchases
FROM ML.PREDICT(MODEL `bqml_tutorial.sample_model`, (
SELECT
IFNULL(device.operatingSystem, "") AS os,
device.isMobile AS is_mobile,
IFNULL(totals.pageviews, 0) AS pageviews,
IFNULL(geoNetwork.country, "") AS countr... | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
When the query is complete, the results appear below the query. The
results should look like the following:
Cleaning up
To delete the resources created by this tutorial, execute the following code to delete the dataset and its contents: | client.delete_dataset(dataset, delete_contents=True) | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Consider a project with the following characteristics: | I = 75 # Lump sum investment to start project
Xs = 100 # project success return
Xf = 0 # project failure return
p = 0.95 # probability of success when diligent
q = 0.50 # probability of success when non-diligent
EX = E(Xs,Xf,p) # Gross expected project return
ubar = 5 # Con... | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
This project fails only 1 percent of the time when the agent is non-diligent (corrupt) but fails 50 percent of the time when they are non-diligent (corrupt). We associate non-diligence with an opportunity to divert $\bar B$ in funds to private uses. | B = 10 | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
As derived above the optimal renumeration contract calls for the agent to pay a big fine for failure and earn a positive reward for success: | cf = -p*B/(p-q) + ubar
cs = (1-p)*B/(p-q) + ubar
print('(c_f, c_s) =({:5.1f}{:5.1f})'.format(cf, cs))
print('consumer and bank expected payments:')
E(cs,cf,p), E(Xs-cs, Xf-cf,p) - I | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
In expectation this covers the agent's opportunity cost of funds $\bar u$. Since the incentive compatibility constraint is met (by construction) when she is diligent:
Diagram | def zeroprofit(c):
return EX/p -((1-p)/p)*c - I/p
def IC(c):
return c + B/(p-q)
def BPC(c,ubar):
return ubar/p - ((1-p)/p)*c
cf_min, cf_max = -25,10
c = np.arange(cf_min, cf_max)
ax = plt.subplot(111)
ax.plot(c,zeroprofit(c), 'k--',label='zero $\Pi$')
ax.plot(c,IC(c), label='IC')
ax.plot(c,BPC(c,ubar), ... | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
The principal extracts | EX - I - ubar | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
Under this contract the agent will be diligent even though they cannot be observed. Had they been non-dilig | q*(Xs- cs) + (1-q)*(Xf-cf) - I | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
Limited Liability constraints
In the example above the agent is asked to pay the principal in the event of failure ($c_f <0$). Suppose however that the agent cannot be made to pay the fine (e.g. they cannot post bond and run away before paying the fine).
Suppose in fact that the worst fine we can impose is that they ... | cf = -5
cs = -5 + B/(p-q) | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
Which then means that in expectation the agent earns an information rent of | E(cs,cf,p) | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
This is above their reservation utility $bar u$ and this contract is therefore quite a bit more expensive to the principal. Their net return is now
$$E(X,p) - I - E(C,p)$$
$$E(X,p) - I - p/(p-q)$$
And the net benefits to the project are greatly reduced to: | EX - I - E(cs,cf,p) | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
The net benefits have been reduced by the heavy cost of incentive contract to keep the agent diligent or non-corrupt.
But this is still better than allowing the agent to be corrupt. | q*(Xs-cs)+(1-q)*(Xf-cf) - I | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
As we can see from the diagram above the principal can contract with agents who face limited liability but they earn less from agents where the LL constraint binds. The limited liability constraint means the agent must earn a rent in excess of their reservation utility.
Suppose the most we can take away from the agen... | Amc = p*B/(p-q) - (EX - I)
Amc | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
This is an important expression. This tells us that unless the agent can post a minimum bond or collateral of this amount then the principal cannot provide them with strong enough incentives for them to be diligent and still allow the principal to break even on the transaction.
The take away lesson is that sometimes ... | m = np.linspace(0,10,20)
plt.plot(m, EX - I - p*(B/(1+m))/D - m) | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
Which shows that over a range monitoring by the intermediary lowers the information rent that must be left with the agent faster than the cost of monitoring but eventually diminishing returns to this activity kick in (at somewhat less than 4 units of monitoring).
Who monitors the monitor? Two-layered moral hazard
More ... | plt.plot(m, EX - I - p*(B/(1+m))/D - m)
plt.plot(m, EX - I - p*(B/(1+m))/D - p*m/D,'r--') | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
In the competitive scenario more monitoring is employed but this monitoring is effective at bringing down the total cost of implementation, leaving more net project benefits. When the market for intermediaries is not competitive (and/or intermediaries are subject to limited liability constraints themselves) then monit... | EX - I | notebooks/incentives_corruption.ipynb | jhconning/Dev-II | bsd-3-clause |
Now we load the data | # First we load the file
file_location = '../results_database/text_wall_street_big.hdf5'
run_name = '/low-resolution'
f = h5py.File(file_location, 'r')
# Now we need to get the letters and align them
text_directory = '../data/wall_street_letters.npy'
letters_sequence = np.load(text_directory)
Nletters = len(letters_... | presentations/2016-01-26(Wall-Street-Letters-Support-Vector-Machines-Study).ipynb | h-mayorquin/time_series_basic | bsd-3-clause |
Number of data requiered for good predictions.
First let's see how much data we actually require to make good predictions using both a linear and an RBF kernel for a support vector machine. | number_of_data = np.logspace(2, 3.5, 10, dtype='int')
delay = 5
cache_size = 5000
accuracy_linear = []
accuracy_rbf = []
accuracy_linear_std = []
accuracy_rbf_std = []
for N in number_of_data:
# Standarized
X = SLM[:,:(N - delay)].T
y = letters_sequence[delay:N]
# We now scale X
X = preprocessing... | presentations/2016-01-26(Wall-Street-Letters-Support-Vector-Machines-Study).ipynb | h-mayorquin/time_series_basic | bsd-3-clause |
Plot it | gs = gridspec.GridSpec(1, 2)
fig = plt.figure(figsize=(12, 9))
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(number_of_data, accuracy_linear, 'o-', lw=2, markersize=10, label='linear')
ax1.plot(number_of_data, accuracy_rbf, 'o-', lw=2, markersize=10, label='rbf')
ax1.set_xlabel('Total Data')
ax1.set_ylabel('Accuracy %')
ax... | presentations/2016-01-26(Wall-Street-Letters-Support-Vector-Machines-Study).ipynb | h-mayorquin/time_series_basic | bsd-3-clause |
Latency analysis for SMVs | delays = np.arange(0, 10)
N = 1000
accuracy_lattency = []
for delay in delays:
# Standarized
print(delay)
X = SLM[:,:(N - delay)].T
y = letters_sequence[delay:N]
# We now scale X
X = preprocessing.scale(X)
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size... | presentations/2016-01-26(Wall-Street-Letters-Support-Vector-Machines-Study).ipynb | h-mayorquin/time_series_basic | bsd-3-clause |
Plot it | plt.plot(delays, accuracy_lattency, 'o-', lw=2, markersize=10., label='Accuracy')
plt.xlabel('Delays')
plt.ylim([0, 105])
plt.xlim([-0.5, 10])
plt.ylabel('Accuracy %')
plt.title('Delays vs Accuracy')
fig = plt.gcf()
fig.set_size_inches((12, 9))
plt.legend() | presentations/2016-01-26(Wall-Street-Letters-Support-Vector-Machines-Study).ipynb | h-mayorquin/time_series_basic | bsd-3-clause |
Interpolation with RBF
$$
f( x) =\sum ^{P}{p=1} a{p} .R_{p} +b
$$
$$
R_{p} = e^{-\frac{1}{2\sigma ^{2}} .\parallel ( X_{i}) -( X_{p}) \parallel ^{2}}
$$
$$
\sigma =\frac{P_{max} -P_{min}}{\sqrt{2P}}
$$
$$
\sigma =\frac{4-2}{\sqrt{2.2}} \
$$
$$
\sigma ^{2} =1
$$
$$
C_{1}=2
$$
$$
C_{2}=4
$$
$$\displaystyle \frac{1}{[ R]... | def rbf(inp, out, center):
def euclidean_norm(x1, x2):
return sqrt(((x1 - x2)**2).sum(axis=0))
def gaussian (x, c):
return exp(+1 * pow(euclidean_norm(x, c), 2))
R = np.ones((len(inp), (len(center) + 1)))
for i, iv in enumerate(inp):
for j, jv in enumerate(center):
... | _notebooks/Radial basis function.ipynb | tiagofabre/tiagofabre.github.io | mit |
inp = np.array([2, 3, 4])
out = np.array([3, 6, 5])
center = np.array([2, 4])
rbf_instance = rbf(inp, out, center)
input_test = input_test = np.linspace(0,10,100)
output_test = list(map(rbf_instance, input_test))
plt.plot(input_test, output_test)
plt.plot(inp, out, 'ro')
plt.ylabel('expected vs predicted')
plt.savef... | _notebooks/Radial basis function.ipynb | tiagofabre/tiagofabre.github.io | mit | |
inp = np.array([2, 3, 4, 5])
out = np.array([3, 1, 5, -2])
center = np.array([2, 3, 4])
rbf_instance = rbf(inp, out, center)
input_test = np.linspace(-5,10,100)
output_test = list(map(rbf_instance, input_test))
# plt.plot(input_test, output_test)
plt.plot(inp, out, 'ro')
plt.ylabel('expected vs predicted')
plt.savef... | _notebooks/Radial basis function.ipynb | tiagofabre/tiagofabre.github.io | mit | |
inp = np.array([2, 3, 4, 5])
out = np.array([3, 1, 5, -2])
center = np.array([2, 3, 4])
rbf_instance = rbf(inp, out, center)
input_test = input_test = np.linspace(2,5,100)
output_test = list(map(rbf_instance, input_test))
plt.plot(input_test, output_test)
plt.plot(inp, out, 'ro')
plt.ylabel('expected vs predicted')
... | _notebooks/Radial basis function.ipynb | tiagofabre/tiagofabre.github.io | mit | |
XOR input | inp = np.array([np.array([1,1]), np.array([0,1]), np.array([0,0]), np.array([1,0])])
out = np.array([ 0, 1, 0, 1])
center = np.array([ np.array([1,1]), np.array([0,0])])
rbf_instance = rbf(inp, out, center)
inp_test = np.array([np.array([1,1]),
... | _notebooks/Radial basis function.ipynb | tiagofabre/tiagofabre.github.io | mit |
TPU or GPU detection | try: # detect TPUs
tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()
strategy = tf.distribute.TPUStrategy(tpu)
except ValueError: # detect GPUs or multi-GPU machines
strategy = tf.distribute.MirroredStrategy()
print("REPLICAS: ", strategy.num_replicas_in_sync) | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Configuration | GCS_DS_PATH = "gs://practical-ml-vision-book/flowers_5_tfr"
# Settings for TPUv3. When running on hardware with less memory such as a TPUv2 (Colab)
# or a GPU, you might have to use lower BATCH_SIZE and/or IMAGE_SIZE values.
IMAGE_SIZE = [224, 224] # available image sizes in flowers104 dataset: 512x512, 331x331, 224x... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Visualization utilities
data -> pixels, nothing of much interest for the machine learning practitioner in this section. | # numpy and matplotlib defaults
np.set_printoptions(threshold=15, linewidth=80)
def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object: # binary string in this case, these are image ID strings
... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Datasets | def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3) # decoded inamge in uint8 format range [0,255]
image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU
return image
def read_tfrecord(example):
TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Dataset visualizations (5 flowers) | # data dump
print("Training data shapes:")
for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
print("Training data label examples:", label.numpy())
# Peek at training data
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Model | with strategy.scope():
pretrained_model = tf.keras.applications.MobileNetV2(
weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE, 3])
pretrained_model.trainable = True # fine-tuning
model = tf.keras.Sequential([
tf.keras.layers.Lambda( # convert image fo... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Training | history = model.fit(get_training_dataset(), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS,
validation_data=get_validation_dataset(), validation_steps=VALIDATION_STEPS,
callbacks=[lr_callback])
display_training_curves(history.history['loss'], history.history['val_loss'], 'loss',... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Confusion matrix | cmdataset = get_validation_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and labels, order matters.
images_ds = cmdataset.map(lambda image, label: image)
labels_ds = cmdataset.map(lambda image, label: label).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALI... | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Visual validation | dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
batch = iter(dataset)
# run this cell again for next set of images
images, labels = next(batch)
probabilities = model.predict(images)
predictions = np.argmax(probabilities, axis=-1)
display_batch_of_images((images, labels), predictions) | 03_image_models/03b_finetune_MOBILENETV2_flowers5.ipynb | GoogleCloudPlatform/practical-ml-vision-book | apache-2.0 |
Interact basics
Write a print_sum function that prints the sum of its arguments a and b. | def print_sum(a, b):
"""Print the sum of the arguments a and b."""
print(a+b) | assignments/assignment05/InteractEx01.ipynb | joshnsolomon/phys202-2015-work | mit |
Use the interact function to interact with the print_sum function.
a should be a floating point slider over the interval [-10., 10.] with step sizes of 0.1
b should be an integer slider the interval [-8, 8] with step sizes of 2. | interact(print_sum,a=(-10.,10.,.1),b=(-8,8,2));
assert True # leave this for grading the print_sum exercise | assignments/assignment05/InteractEx01.ipynb | joshnsolomon/phys202-2015-work | mit |
Write a function named print_string that prints a string and additionally prints the length of that string if a boolean parameter is True. | def print_string(s, length=False):
"""Print the string s and optionally its length."""
print(s)
if length == True:
print(len(s)) | assignments/assignment05/InteractEx01.ipynb | joshnsolomon/phys202-2015-work | mit |
Use the interact function to interact with the print_string function.
s should be a textbox with the initial value "Hello World!".
length should be a checkbox with an initial value of True. | # YOUR CODE HERE
interact(print_string,s='Hello World!',length=True);
assert True # leave this for grading the print_string exercise | assignments/assignment05/InteractEx01.ipynb | joshnsolomon/phys202-2015-work | mit |
Load dataset
Data is a csv file with each column as features and rows as samples of positive and negative candidates
Class label is the last column where "1" correspondes to true pulsar candidate and "0" a false candidate | data = pd.read_csv('Data/pulsar.csv')
# Show some information
print ('Dataset has %d rows and %d columns including features and labels'%(data.shape[0],data.shape[1])) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Lets print the feature names | print (data.columns.values[0:-1]) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Do a scatter plot | ax = plt.figure().gca(projection='3d')
ax.scatter3D(data['std_pf'], data['mean_dm'], data['mean_int_pf'],c=data['class'],alpha=.25)
ax.set_xlabel('std_pf')
ax.set_ylabel('mean_dm')
ax.set_zlabel('mean_int_pf') | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Get the features and labels | # Lets shuffle the rows of the data 10 times
for i in range(10):
data = shuffle(data)
# Now split the dataset into seperate variabels for features and labels
features = data.ix[:,data.columns != 'class'].values # All columns except class
labels = data['class'].values # Class labels | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Split data to training and validation sets | # Do a 70 - 30 split of the whole data for training and testing
# The last argument specifies the fraction of samples for testing
train_data,test_data,train_labels,test_labels = train_test_split(features,labels,test_size=.3)
#Print some info
print ('Number of training data points : %d'%(train_data.shape[0]))
print ('Nu... | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Lets do the training on different algorithms
We will be using the following algorithms
k-Nearest Neighbours (KNN) [ https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm ]
Naive Bayes Classifier [ https://en.wikipedia.org/wiki/Naive_Bayes_classifier ]
Multilayer Neural Network [ https://en.wikipedia.org/wik... | # K nearest neighbor
knn = KNeighborsClassifier()
knn.fit(train_data,train_labels) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Scikit Naive Bayes
http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html | # Naive Bayes
nb = GaussianNB()
nb.fit(train_data,train_labels) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Scikit MLP
https://en.wikipedia.org/wiki/Multilayer_perceptron | # MLP
mlp = MLPClassifier(solver='sgd',hidden_layer_sizes=(5, 1))
mlp.fit(train_data,train_labels) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Fancy function to print results for model evaluation | # Pretty function to test a model and print accuracy score
def evaluate(model,modelname,test_data,test_labels):
predictions = model.predict(test_data) # Do the actual prediction
print('====================================================')
print('Classification Report for %s'%modelname)
print('========... | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
Now Lets test each classifier and disply their accuracy | for i in range(0,3):
evaluate(models[i],model_names[i],test_data,test_labels) | Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/Predicting_Pulsar_Candidates.ipynb | astro4dev/OAD-Data-Science-Toolkit | gpl-3.0 |
一般的数据抓取,使用urllib2和beautifulsoup配合就可以了。
尤其是对于翻页时url出现规则变化的网页,只需要处理规则化的url就可以了。
以简单的例子是抓取天涯论坛上关于某一个关键词的帖子。
在天涯论坛,关于雾霾的帖子的第一页是:
http://bbs.tianya.cn/list.jsp?item=free&nextid=0&order=8&k=雾霾
第二页是:
http://bbs.tianya.cn/list.jsp?item=free&nextid=1&order=8&k=雾霾
Beautiful Soup
Beautiful Soup is a Python library designed fo... | url = 'file:///Users/chengjun/GitHub/cjc2016/data/test.html'
content = urllib2.urlopen(url).read()
soup = BeautifulSoup(content, 'html.parser')
soup | code/04.PythonCrawler_beautifulsoup.ipynb | Aggieyixin/cjc2016 | mit |
html.parser
Beautiful Soup supports the html.parser included in Python’s standard library
lxml
but it also supports a number of third-party Python parsers. One is the lxml parser lxml. Depending on your setup, you might install lxml with one of these commands:
$ apt-get install python-lxml
$ easy_install lxml
$ pip in... | print(soup.prettify()) | code/04.PythonCrawler_beautifulsoup.ipynb | Aggieyixin/cjc2016 | mit |
html
head
title
body
p (class = 'title', 'story' )
a (class = 'sister')
href/id | for tag in soup.find_all(True):
print(tag.name)
soup('head') # or soup.head
soup('body') # or soup.body
soup('title') # or soup.title
soup('p')
soup.p
soup.title.name
soup.title.string
soup.title.text
soup.title.parent.name
soup.p
soup.p['class']
soup.find_all('p', {'class', 'title'})
soup.find_all('... | code/04.PythonCrawler_beautifulsoup.ipynb | Aggieyixin/cjc2016 | mit |
数据抓取:
根据URL抓取微信公众号文章内容
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com | from IPython.display import display_html, HTML
HTML('<iframe src=http://mp.weixin.qq.com/s?__biz=MzA3MjQ5MTE3OA==&\
mid=206241627&idx=1&sn=471e59c6cf7c8dae452245dbea22c8f3&3rd=MzA3MDU4NTYzMw==&scene=6#rd\
width=500 height=500></iframe>')
# the webpage we would like to crawl | code/04.PythonCrawler_beautifulsoup.ipynb | Aggieyixin/cjc2016 | mit |
查看源代码
Inspect | url = "http://mp.weixin.qq.com/s?__biz=MzA3MjQ5MTE3OA==&\
mid=206241627&idx=1&sn=471e59c6cf7c8dae452245dbea22c8f3&3rd=MzA3MDU4NTYzMw==&scene=6#rd"
content = urllib2.urlopen(url).read() #获取网页的html文本
soup = BeautifulSoup(content, 'html.parser')
title = soup.title.text
rmml = soup.find('div', {'class', 'rich_media_meta_l... | code/04.PythonCrawler_beautifulsoup.ipynb | Aggieyixin/cjc2016 | mit |
If the following cell does not reflect the version of tensorflow and tensor2tensor that you just installed, click "Reset Session" on the notebook so that the Python environment picks up the new packages. | %%bash
pip freeze | grep tensor
import os
PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# this is what this notebook is demonstrating
PROBLEM= 'poetry_line_pro... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Download data
We will get some <a href="https://www.gutenberg.org/wiki/Poetry_(Bookshelf)">poetry anthologies</a> from Project Gutenberg. | %%bash
rm -rf data/poetry
mkdir -p data/poetry
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
import re
books = [
# bookid, skip N lines
(26715, 1000, 'Victorian songs'),
(30235, 580, 'Baldwin collection'),
(35402, 710, 'Swinburne collection'),
(574, 15, 'Blake'),
(13... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Create training dataset
We are going to train a machine learning model to write poetry given a starting point. We'll give it one line, and it is going to tell us the next line. So, naturally, we will train it on real poetry. Our feature will be a line of a poem and the label will be next line of that poem.
<p>
Our tra... | with open('data/poetry/raw.txt', 'r') as rawfp,\
open('data/poetry/input.txt', 'w') as infp,\
open('data/poetry/output.txt', 'w') as outfp:
prev_line = ''
for curr_line in rawfp:
curr_line = curr_line.strip()
# poems break at empty lines, so this ensures we train only
# on lines... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
We do not need to generate the data beforehand -- instead, we can have Tensor2Tensor create the training dataset for us. So, in the code below, I will use only data/poetry/raw.txt -- obviously, this allows us to productionize our model better. Simply keep collecting raw data and generate the training/test data at the ... | %%bash
rm -rf poetry
mkdir -p poetry/trainer
%%writefile poetry/trainer/problem.py
import os
import tensorflow as tf
from tensor2tensor.utils import registry
from tensor2tensor.models import transformer
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_encoder
from tensor... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Generate training data
Our problem (translation) requires the creation of text sequences from the training dataset. This is done using t2t-datagen and the Problem defined in the previous section.
(Ignore any runtime warnings about np.float64. they are harmless). | %%bash
DATA_DIR=./t2t_data
TMP_DIR=$DATA_DIR/tmp
rm -rf $DATA_DIR $TMP_DIR
mkdir -p $DATA_DIR $TMP_DIR
# Generate data
t2t-datagen \
--t2t_usr_dir=./poetry/trainer \
--problem=$PROBLEM \
--data_dir=$DATA_DIR \
--tmp_dir=$TMP_DIR | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's check to see the files that were output. If you see a broken pipe error, please ignore. | !ls t2t_data | head | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Provide Cloud ML Engine access to data
Copy the data to Google Cloud Storage, and then provide access to the data. gsutil throws an error when removing an empty bucket, so you may see an error the first time this code is run. | %%bash
DATA_DIR=./t2t_data
gsutil -m rm -r gs://${BUCKET}/poetry/
gsutil -m cp ${DATA_DIR}/${PROBLEM}* ${DATA_DIR}/vocab* gs://${BUCKET}/poetry/data
%%bash
PROJECT_ID=$PROJECT
AUTH_TOKEN=$(gcloud auth print-access-token)
SVC_ACCOUNT=$(curl -X GET -H "Content-Type: application/json" \
-H "Authorization: Bearer $AUT... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Train model locally on subset of data
Let's run it locally on a subset of the data to make sure it works. | %%bash
BASE=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/subset
gsutil -m rm -r $OUTDIR
gsutil -m cp \
${BASE}/${PROBLEM}-train-0008* \
${BASE}/${PROBLEM}-dev-00000* \
${BASE}/vocab* \
$OUTDIR | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Note: the following will work only if you are running Jupyter on a reasonably powerful machine. Don't be alarmed if your process is killed. | %%bash
DATA_DIR=gs://${BUCKET}/poetry/subset
OUTDIR=./trained_model
rm -rf $OUTDIR
t2t-trainer \
--data_dir=gs://${BUCKET}/poetry/subset \
--t2t_usr_dir=./poetry/trainer \
--problem=$PROBLEM \
--model=transformer \
--hparams_set=transformer_poetry \
--output_dir=$OUTDIR --job-dir=$OUTDIR --train_steps=10 | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Option 1: Train model locally on full dataset (use if running on Notebook Instance with a GPU)
You can train on the full dataset if you are on a Google Cloud Notebook Instance with a P100 or better GPU | %%bash
LOCALGPU="--train_steps=7500 --worker_gpu=1 --hparams_set=transformer_poetry"
DATA_DIR=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/model
rm -rf $OUTDIR
t2t-trainer \
--data_dir=gs://${BUCKET}/poetry/subset \
--t2t_usr_dir=./poetry/trainer \
--problem=$PROBLEM \
--model=transformer \
--hpar... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Option 2: Train on Cloud ML Engine
tensor2tensor has a convenient --cloud_mlengine option to kick off the training on the managed service.
It uses the Python API mentioned in the Cloud ML Engine docs, rather than requiring you to use gcloud to submit the job.
<p>
Note: your project needs P100 quota in the region.
<p>
T... | %%bash
GPU="--train_steps=7500 --cloud_mlengine --worker_gpu=1 --hparams_set=transformer_poetry"
DATADIR=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/model
JOBNAME=poetry_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
yes Y | t2t-trainer \
--data_dir=gs://${BUCKET}/poetry... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
The job took about <b>25 minutes</b> for me and ended with these evaluation metrics:
<pre>
Saving dict for global step 8000: global_step = 8000, loss = 6.03338, metrics-poetry_line_problem/accuracy = 0.138544, metrics-poetry_line_problem/accuracy_per_sequence = 0.0, metrics-poetry_line_problem/accuracy_top5 = 0.232037,... | %%bash
# use one of these
TPU="--train_steps=7500 --use_tpu=True --cloud_tpu_name=laktpu --hparams_set=transformer_poetry_tpu"
DATADIR=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/model_tpu
JOBNAME=poetry_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
echo "'Y'" | t2t-train... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
The job took about <b>10 minutes</b> for me and ended with these evaluation metrics:
<pre>
Saving dict for global step 8000: global_step = 8000, loss = 6.03338, metrics-poetry_line_problem/accuracy = 0.138544, metrics-poetry_line_problem/accuracy_per_sequence = 0.0, metrics-poetry_line_problem/accuracy_top5 = 0.232037,... | %%bash
XXX This takes 3 hours on 4 GPUs. Remove this line if you are sure you want to do this.
DATADIR=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/model_full2
JOBNAME=poetry_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
echo "'Y'" | t2t-trainer \
--data_dir=gs://${BUCK... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
This job took <b>12 hours</b> for me and ended with these metrics:
<pre>
global_step = 76000, loss = 4.99763, metrics-poetry_line_problem/accuracy = 0.219792, metrics-poetry_line_problem/accuracy_per_sequence = 0.0192308, metrics-poetry_line_problem/accuracy_top5 = 0.37618, metrics-poetry_line_problem/approx_bleu_score... | %%bash
gsutil ls gs://${BUCKET}/poetry/model #_modeltpu | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Batch-predict
How will our poetry model do when faced with Rumi's spiritual couplets? | %%writefile data/poetry/rumi.txt
Where did the handsome beloved go?
I wonder, where did that tall, shapely cypress tree go?
He spread his light among us like a candle.
Where did he go? So strange, where did he go without me?
All day long my heart trembles like a leaf.
All alone at midnight, where did that beloved go?
G... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's write out the odd-numbered lines. We'll compare how close our model can get to the beauty of Rumi's second lines given his first. | %%bash
awk 'NR % 2 == 1' data/poetry/rumi.txt | tr '[:upper:]' '[:lower:]' | sed "s/[^a-z\'-\ ]//g" > data/poetry/rumi_leads.txt
head -3 data/poetry/rumi_leads.txt
%%bash
# same as the above training job ...
TOPDIR=gs://${BUCKET}
OUTDIR=${TOPDIR}/poetry/model #_tpu # or ${TOPDIR}/poetry/model_full
DATADIR=${TOPDIR}/p... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<b> Note </b> if you get an error about "AttributeError: 'HParams' object has no attribute 'problems'" please <b>Reset Session</b>, run the cell that defines the PROBLEM and run the above cell again. | %%bash
DECODE_FILE=data/poetry/rumi_leads.txt
cat ${DECODE_FILE}.*.decodes | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Some of these are still phrases and not complete sentences. This indicates that we might need to train longer or better somehow. We need to diagnose the model ...
<p>
### Diagnosing training run
<p>
Let's diagnose the training run to see what we'd improve the next time around.
(Note that this package may not be prese... | from google.datalab.ml import TensorBoard
TensorBoard().start('gs://{}/poetry/model_full'.format(BUCKET))
for pid in TensorBoard.list()['pid']:
TensorBoard().stop(pid)
print('Stopped TensorBoard with pid {}'.format(pid)) | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<table>
<tr>
<td><img src="diagrams/poetry_loss.png"/></td>
<td><img src="diagrams/poetry_acc.png"/></td>
</table>
Looking at the loss curve, it is clear that we are overfitting (note that the orange training curve is well below the blue eval curve). Both loss curves and the accuracy-per-sequence curve, which is our ke... | %%bash
XXX This takes about 15 hours and consumes about 420 ML units. Uncomment if you wish to proceed anyway
DATADIR=gs://${BUCKET}/poetry/data
OUTDIR=gs://${BUCKET}/poetry/model_hparam
JOBNAME=poetry_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
echo "'Y'" | t2t-trainer \
--dat... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
When I ran the above job, it took about 15 hours and finished with these as the best parameters:
<pre>
{
"trialId": "37",
"hyperparameters": {
"hp_num_hidden_layers": "4",
"hp_learning_rate": "0.026711152525921437",
"hp_hidden_size": "512",
"hp_attention_dropout": "0.60589466... | %%bash
# same as the above training job ...
BEST_TRIAL=28 # CHANGE as needed.
TOPDIR=gs://${BUCKET}
OUTDIR=${TOPDIR}/poetry/model_hparam/$BEST_TRIAL
DATADIR=${TOPDIR}/poetry/data
MODEL=transformer
HPARAMS=transformer_poetry
# the file with the input lines
DECODE_FILE=data/poetry/rumi_leads.txt
BEAM_SIZE=4
ALPHA=0.6
... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Take the first three line. I'm showing the first line of the couplet provided to the model, how the AI model that we trained complets it and how Rumi completes it:
<p>
INPUT: where did the handsome beloved go <br/>
AI: where art thou worse to me than dead <br/>
RUMI: I wonder, where did that tall, shapely cypress tree ... | %%bash
TOPDIR=gs://${BUCKET}
OUTDIR=${TOPDIR}/poetry/model_full2
DATADIR=${TOPDIR}/poetry/data
MODEL=transformer
HPARAMS=transformer_poetry
BEAM_SIZE=4
ALPHA=0.6
t2t-exporter \
--model=$MODEL \
--hparams_set=$HPARAMS \
--problem=$PROBLEM \
--t2t_usr_dir=./poetry/trainer \
--decode_hparams="beam_size=$BEAM_SI... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Cloud ML Engine | %%writefile mlengine.json
description: Poetry service on ML Engine
autoScaling:
minNodes: 1 # We don't want this model to autoscale down to zero
%%bash
MODEL_NAME="poetry"
MODEL_VERSION="v1"
MODEL_LOCATION=$(gsutil ls gs://${BUCKET}/poetry/model_full2/export/Servo | tail -1)
echo "Deleting and deploying $MODEL_NA... | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Kubeflow
Follow these instructions:
* On the GCP console, launch a Google Kubernetes Engine (GKE) cluster named 'poetry' with 2 nodes, each of which is a n1-standard-2 (2 vCPUs, 7.5 GB memory) VM
* On the GCP console, click on the Connect button for your cluster, and choose the CloudShell option
* In CloudShell, run:
... | !cat application/app.yaml
%%bash
cd application
#gcloud app create # if this is your first app
#gcloud app deploy --quiet --stop-previous-version app.yaml | courses/machine_learning/deepdive/09_sequence_keras/poetry.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Variables can be classified as qualitative (aka, categorical) or quantitative (aka, numeric).
Qualitative: Qualitative variables take on values that are names or labels. The eye color (e.g., brown, green, gray, etc.) or the sex of the person (e.g., female, male) would be examples of qualitative or categorical variabl... | print(type(df["Sex"])) | notes/03 - Introduction to Data Cleaning.ipynb | f-guitart/data_mining | gpl-3.0 |
And what kind of variable is for example the weight of a person? | print(df["Age[years]"].dtype) | notes/03 - Introduction to Data Cleaning.ipynb | f-guitart/data_mining | gpl-3.0 |
And what about categorical variables? Well, that deserve more than a word, so commonly for us categorical variables will have object dtype. | print(df["Sex"].dtype)
print (df["Eye Color"].dtype) | notes/03 - Introduction to Data Cleaning.ipynb | f-guitart/data_mining | gpl-3.0 |
To know more about this, give a read to these links:
* http://stackoverflow.com/questions/21018654/strings-in-a-dataframe-but-dtype-is-object
* http://pandas.pydata.org/pandas-docs/stable/categorical.html
* http://pandas.pydata.org/pandas-docs/version/0.15.2/text.html
Special Values
There are some values that are consi... | import pandas as pd
df = pd.read_csv('../data/people_with_nas.csv',index_col=0,na_values="NaN")
print(df)
print(df["Weight[kg]"])
pd.isnull(df["Weight[kg]"]) | notes/03 - Introduction to Data Cleaning.ipynb | f-guitart/data_mining | gpl-3.0 |
You should be asking yourself... Why using np.nan and not None
The answer is (or at least should be) that np.nan allows vectorized operations. | import numpy as np
v1 = pd.Series([1,2,3,4])
v2 = pd.Series([1,2,None,4])
v3 = pd.Series([1,2,np.nan,4])
# this can arise problems
print(v1 * v2)
# this shouldn't
print(v2 * v3) | notes/03 - Introduction to Data Cleaning.ipynb | f-guitart/data_mining | gpl-3.0 |
The $p$-value is 0.43, so it could be normal
Problem 2.2
Given $\hat{\alpha} = 0.2$, $\hat{\beta} = 1.6$, $N = 11$, $S^2_\alpha = 0.4$, $S^2_\epsilon = 0.5$, $S^2_\beta = 4$, give a justification for or against their being an intercept | import numpy as np
T = (0.2 - 0) / np.sqrt(0.4)
# Use 11 - 1 because null hypothesis is there is no intercept!
1 - (ss.t.cdf(T, 11 - 1) - ss.t.cdf(-T, 11- 1)) | unit_12/hw_2017/problem_set_1.ipynb | whitead/numerical_stats | gpl-3.0 |
The $p$-value is 0.76, so we cannot reject the null hypothesis of no intercept
Problem 2.3
Conduct a hpyothesis test for the slope being positive using the above data. This is a one-sided hypothesis test. Hint: a good null hypothesis would be that the slope is negative. Describe your test in Markdown first, then comple... | T = 1.6 / np.sqrt(4)
ss.t.cdf(T, 11 - 1) - ss.t.cdf(0,11 - 1) | unit_12/hw_2017/problem_set_1.ipynb | whitead/numerical_stats | gpl-3.0 |
The $p$-value is 0.28, so it's not guaranteed that the slope is positive. This is due to the large uncertainty in the intercept
Problem 2.4
Write a function which computes the SSR for $\hat{y} = \beta_0 x + \beta_1 \exp\left( -\beta_2 x\right) $. Your function should take in one argument. You may assume $x$ and $y$ are... | def ssr(beta):
yhat = beta[0] * x + beta[1] * np.exp(-beta[2] * x)
return np.sum( (y - yhat)**2) | unit_12/hw_2017/problem_set_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Change the following cell as necessary: | # Change with your own bucket and project below:
BUCKET = "<BUCKET>"
PROJECT = "<PROJECT>"
OUTDIR = "gs://{bucket}/taxifare/data".format(bucket=BUCKET)
os.environ['BUCKET'] = BUCKET
os.environ['OUTDIR'] = OUTDIR
os.environ['PROJECT'] = PROJECT | courses/machine_learning/deepdive2/building_production_ml_systems/solutions/0_export_data_from_bq_to_gcs.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create BigQuery tables
If you haven not already created a BigQuery dataset for our data, run the following cell: | bq = bigquery.Client(project = PROJECT)
dataset = bigquery.Dataset(bq.dataset("taxifare"))
try:
bq.create_dataset(dataset)
print("Dataset created")
except:
print("Dataset already exists") | courses/machine_learning/deepdive2/building_production_ml_systems/solutions/0_export_data_from_bq_to_gcs.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Let's create a table with 1 million examples.
Note that the order of columns is exactly what was in our CSV files. | %%bigquery
CREATE OR REPLACE TABLE taxifare.feateng_training_data AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_datetime,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS pas... | courses/machine_learning/deepdive2/building_production_ml_systems/solutions/0_export_data_from_bq_to_gcs.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Make the validation dataset be 1/10 the size of the training dataset. | %%bigquery
CREATE OR REPLACE TABLE taxifare.feateng_valid_data AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_datetime,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS passen... | courses/machine_learning/deepdive2/building_production_ml_systems/solutions/0_export_data_from_bq_to_gcs.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Export the tables as CSV files | %%bash
echo "Deleting current contents of $OUTDIR"
gsutil -m -q rm -rf $OUTDIR
echo "Extracting training data to $OUTDIR"
bq --location=US extract \
--destination_format CSV \
--field_delimiter "," --noprint_header \
taxifare.feateng_training_data \
$OUTDIR/taxi-train-*.csv
echo "Extracting validation d... | courses/machine_learning/deepdive2/building_production_ml_systems/solutions/0_export_data_from_bq_to_gcs.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Import statements | import rasterio
import fiona
import pandas
import numpy
from pyproj import Proj, transform
from fiona.crs import from_epsg
with fiona.open(sample_points_filepath, 'r') as source_points:
points = [f['geometry']['coordinates'] for f in source_points]
original = Proj(source_points.crs)
destination = Proj... | examples/Playing with rasterio and fiona.ipynb | jacobdein/alpine-soundscapes | mit |
Transform points | points_projected = []
for p in points:
x, y = p
lat, long = transform(original, destination, x, y)
points_projected.append((long,lat))
points_projected_pd = pandas.DataFrame(points_projected, columns=["lat", "long"])
with fiona.open(sample_points_filepath, 'r') as source_points:
names = numpy.array([p... | examples/Playing with rasterio and fiona.ipynb | jacobdein/alpine-soundscapes | mit |
Fairness Indicators TensorBoard Plugin Example Colab
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/responsible_ai/fairness_indicators/tutorials/Fairness_indicators_TensorBoard_Plugin_Example_Colab"><img src="https://www.tensorflow.org/images/tf_logo_32p... | !pip install -q -U pip==20.2
!pip install fairness_indicators 'absl-py<0.9,>=0.7'
!pip install google-api-python-client==1.8.3
!pip install tensorboard-plugin-fairness-indicators
!pip install tensorflow-serving-api==2.8.0 | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Restart the runtime. After the runtime is restarted, continue with following cells without running previous cell again. | # %tf.disable_v2_behavior() # Uncomment this line if running in Google Colab.
import datetime
import os
import tempfile
from tensorboard_plugin_fairness_indicators import summary_v2
import tensorflow.compat.v1 as tf
# example_model.py is provided in fairness_indicators package to train and
# evaluate an example model... | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Data and Constants | # To know about dataset, check Fairness Indicators Example Colab at:
# https://github.com/tensorflow/fairness-indicators/blob/master/g3doc/tutorials/Fairness_Indicators_Example_Colab.ipynb
train_tf_file = tf.keras.utils.get_file('train.tf', 'https://storage.googleapis.com/civil_comments_dataset/train_tf_processed.tfre... | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Train the Model | model_dir = os.path.join(BASE_DIR, 'train',
datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
classifier = example_model.train_model(model_dir,
train_tf_file,
LABEL,
TEXT_FEATU... | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Run TensorFlow Model Analysis with Fairness Indicators
This step might take 2 to 5 minutes. | tfma_eval_result_path = os.path.join(BASE_DIR, 'tfma_eval_result')
example_model.evaluate_model(classifier,
validate_tf_file,
tfma_eval_result_path,
'gender',
LABEL,
FEATURE_... | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Visualize Fairness Indicators in TensorBoard
Below you will visualize Fairness Indicators in Tensorboard and compare performance of each slice of the data on selected metrics. You can adjust the baseline comparison slice as well as the displayed threshold(s) using the drop down menus at the top of the visualization. Yo... | import tensorflow.compat.v2 as tf2
writer = tf2.summary.create_file_writer(
os.path.join(model_dir, 'fairness_indicators'))
with writer.as_default():
summary_v2.FairnessIndicators(tfma_eval_result_path, step=1)
writer.close() | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Launch TensorBoard
Navigate to "Fairness Indicators" tab to visualize Fairness Indicators. | %load_ext tensorboard
%tensorboard --logdir=$model_dir | g3doc/tutorials/Fairness_Indicators_TensorBoard_Plugin_Example_Colab.ipynb | tensorflow/fairness-indicators | apache-2.0 |
Crear graficas (plot)
Crear graficas es muy facil en matplotlib, si tienes una lista de valores X y otra y..solo basta usar : | x = np.array([0,1,2,3,4])
y = x**2 #cuadramos x
plt.plot(x,y)
plt.title("Grafica sencilla")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.