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 |
|---|---|---|---|---|---|
Gradient Boosted Trees: Model understanding View on TensorFlow.org Run in Google Colab View source on GitHub For an end-to-end walkthrough of training a Gradient Boosting model check out the [boosted trees tutorial](./boosted_trees). In this tutorial you will:* Learn how to interpret a Boosted Tr... | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
from IPython.display import clear_output
# Load dataset.
dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')
dfeval = pd.read_csv('https://storage.googleapis.com/... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
For a description of the features, please review the prior tutorial. Create feature columns, input_fn, and the train the estimator Preprocess the data Create the feature columns, using the original numeric columns as is and one-hot-encoding categorical variables. | fc = tf.feature_column
CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',
'embark_town', 'alone']
NUMERIC_COLUMNS = ['age', 'fare']
def one_hot_cat_column(feature_name, vocab):
return fc.indicator_column(
fc.categorical_column_with_vocabulary_list(feature_name,... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Build the input pipeline Create the input functions using the `from_tensor_slices` method in the [`tf.data`](https://www.tensorflow.org/api_docs/python/tf/data) API to read in data directly from Pandas. | # Use entire batch since this is such a small dataset.
NUM_EXAMPLES = len(y_train)
def make_input_fn(X, y, n_epochs=None, shuffle=True):
def input_fn():
dataset = tf.data.Dataset.from_tensor_slices((X.to_dict(orient='list'), y))
if shuffle:
dataset = dataset.shuffle(NUM_EXAMPLES)
# For training, cy... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Train the model | params = {
'n_trees': 50,
'max_depth': 3,
'n_batches_per_layer': 1,
# You must enable center_bias = True to get DFCs. This will force the model to
# make an initial prediction before using any features (e.g. use the mean of
# the training labels for regression or log odds for classification when
# using c... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
For performance reasons, when your data fits in memory, we recommend use the `boosted_trees_classifier_train_in_memory` function. However if training time is not of a concern or if you have a very large dataset and want to do distributed training, use the `tf.estimator.BoostedTrees` API shown above.When using this meth... | in_memory_params = dict(params)
in_memory_params['n_batches_per_layer'] = 1
# In-memory input_fn does not use batching.
def make_inmemory_train_input_fn(X, y):
def input_fn():
return dict(X), y
return input_fn
train_input_fn = make_inmemory_train_input_fn(dftrain, y_train)
# Train the model.
est = tf.estimator... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Model interpretation and plotting | import matplotlib.pyplot as plt
import seaborn as sns
sns_colors = sns.color_palette('colorblind') | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Local interpretabilityNext you will output the directional feature contributions (DFCs) to explain individual predictions using the approach outlined in [Palczewska et al](https://arxiv.org/pdf/1312.1121.pdf) and by Saabas in [Interpreting Random Forests](http://blog.datadive.net/interpreting-random-forests/) (this me... | pred_dicts = list(est.experimental_predict_with_explanations(eval_input_fn))
# Create DFC Pandas dataframe.
labels = y_eval.values
probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])
df_dfc = pd.DataFrame([pred['dfc'] for pred in pred_dicts])
df_dfc.describe().T | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
A nice property of DFCs is that the sum of the contributions + the bias is equal to the prediction for a given example. | # Sum of DFCs + bias == probabality.
bias = pred_dicts[0]['bias']
dfc_prob = df_dfc.sum(axis=1) + bias
np.testing.assert_almost_equal(dfc_prob.values,
probs.values) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Plot DFCs for an individual passenger. Let's make the plot nice by color coding based on the contributions' directionality and add the feature values on figure. | # Boilerplate code for plotting :)
def _get_color(value):
"""To make positive DFCs plot green, negative DFCs plot red."""
green, red = sns.color_palette()[2:4]
if value >= 0: return green
return red
def _add_feature_values(feature_values, ax):
"""Display feature's values on left of plot."""
x_c... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
The larger magnitude contributions have a larger impact on the model's prediction. Negative contributions indicate the feature value for this given example reduced the model's prediction, while positive values contribute an increase in the prediction. You can also plot the example's DFCs compare with the entire distrib... | # Boilerplate plotting code.
def dist_violin_plot(df_dfc, ID):
# Initialize plot.
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
# Create example dataframe.
TOP_N = 8 # View top 8 features.
example = df_dfc.iloc[ID]
ix = example.abs().sort_values()[-TOP_N:].index
example = example[ix]
example_df = exam... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Plot this example. | dist_violin_plot(df_dfc, ID)
plt.title('Feature contributions for example {}\n pred: {:1.2f}; label: {}'.format(ID, probs[ID], labels[ID]))
plt.show() | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Finally, third-party tools, such as [LIME](https://github.com/marcotcr/lime) and [shap](https://github.com/slundberg/shap), can also help understand individual predictions for a model. Global feature importancesAdditionally, you might want to understand the model as a whole, rather than studying individual predictions... | importances = est.experimental_feature_importances(normalize=True)
df_imp = pd.Series(importances)
# Visualize importances.
N = 8
ax = (df_imp.iloc[0:N][::-1]
.plot(kind='barh',
color=sns_colors[0],
title='Gain feature importances',
figsize=(10, 6)))
ax.grid(False, axis='y') | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
2. Average absolute DFCsYou can also average the absolute values of DFCs to understand impact at a global level. | # Plot.
dfc_mean = df_dfc.abs().mean()
N = 8
sorted_ix = dfc_mean.abs().sort_values()[-N:].index # Average and sort by absolute.
ax = dfc_mean[sorted_ix].plot(kind='barh',
color=sns_colors[1],
title='Mean |directional feature contributions|',
figsize... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
You can also see how DFCs vary as a feature value varies. | FEATURE = 'fare'
feature = pd.Series(df_dfc[FEATURE].values, index=dfeval[FEATURE].values).sort_index()
ax = sns.regplot(feature.index.values, feature.values, lowess=True)
ax.set_ylabel('contribution')
ax.set_xlabel(FEATURE)
ax.set_xlim(0, 100)
plt.show() | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
3. Permutation feature importance | def permutation_importances(est, X_eval, y_eval, metric, features):
"""Column by column, shuffle values and observe effect on eval set.
source: http://explained.ai/rf-importance/index.html
A similar approach can be done during training. See "Drop-column importance"
in the above article."""
baseline... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Visualizing model fitting Lets first simulate/create training data using the following formula:$$z=x* e^{-x^2 - y^2}$$Where \(z\) is the dependent variable you are trying to predict and \(x\) and \(y\) are the features. | from numpy.random import uniform, seed
from matplotlib.mlab import griddata
# Create fake data
seed(0)
npts = 5000
x = uniform(-2, 2, npts)
y = uniform(-2, 2, npts)
z = x*np.exp(-x**2 - y**2)
# Prep data for training.
df = pd.DataFrame({'x': x, 'y': y, 'z': z})
xi = np.linspace(-2.0, 2.0, 200),
yi = np.linspace(-2.1,... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
You can visualize the function. Redder colors correspond to larger function values. | zi = griddata(x, y, z, xi, yi, interp='linear')
plot_contour(xi, yi, zi)
plt.scatter(df.x, df.y, marker='.')
plt.title('Contour on training data')
plt.show()
fc = [tf.feature_column.numeric_column('x'),
tf.feature_column.numeric_column('y')]
def predict(est):
"""Predictions from a given estimator."""
predict_... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
First let's try to fit a linear model to the data. | train_input_fn = make_input_fn(df, df.z)
est = tf.estimator.LinearRegressor(fc)
est.train(train_input_fn, max_steps=500);
plot_contour(xi, yi, predict(est)) | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
It's not a very good fit. Next let's try to fit a GBDT model to it and try to understand how the model fits the function. | n_trees = 22 #@param {type: "slider", min: 1, max: 80, step: 1}
est = tf.estimator.BoostedTreesRegressor(fc, n_batches_per_layer=1, n_trees=n_trees)
est.train(train_input_fn, max_steps=500)
clear_output()
plot_contour(xi, yi, predict(est))
plt.text(-1.8, 2.1, '# trees: {}'.format(n_trees), color='w', backgroundcolor='... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Facial Keypoint Detection This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working wit... | # -- DO NOT CHANGE THIS CELL -- #
!mkdir /data
!wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip
!unzip -n /data/train-test-data.zip -d /data
# import the required libraries
import glob
import os
import numpy as np
import pandas as pd
import mat... | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Then, let's load in our training data and display some stats about that dat ato make sure it's been loaded in correctly! | key_pts_frame = pd.read_csv('/data/training_frames_keypoints.csv')
n = 0
image_name = key_pts_frame.iloc[n, 0]
key_pts = key_pts_frame.iloc[n, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
print('Image name: ', image_name)
print('Landmarks shape: ', key_pts.shape)
print('First 4 key pts: {}'.format... | Number of images: 3462
| MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Look at some imagesBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape. | def show_keypoints(image, key_pts):
"""Show image with keypoints"""
plt.imshow(image)
plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m')
# Display a few different types of images by changing the index n
# select an image by index in our data frame
n = 15
image_name = key_pts_frame.iloc[n, ... | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Dataset class and TransformationsTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html). Dataset class``torch.utils.data.Dataset`... | from torch.utils.data import Dataset, DataLoader
class FacialKeypointsDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory... | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Now that we've defined this class, let's instantiate the dataset and display some images. | # Construct the dataset
face_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv',
root_dir='/data/training/')
# print some stats about the dataset
print('Length of dataset: ', len(face_dataset))
# Display a few of the images from the dataset
num_to_disp... | 0 (213, 201, 3) (68, 2)
1 (305, 239, 3) (68, 2)
2 (147, 143, 3) (68, 2)
| MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
TransformsNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.Therefore, we will need to write some pre-processing code.L... | import torch
from torchvision import transforms, utils
# tranforms
class Normalize(object):
"""Convert a color image to grayscale and normalize the color range to [0,1]."""
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
image_copy = np.copy(i... | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Test out the transformsLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescal... | # test out some of these transforms
rescale = Rescale(100)
crop = RandomCrop(50)
composed = transforms.Compose([Rescale(250),
RandomCrop(224)])
# apply the transforms to a sample image
test_num = 500
sample = face_dataset[test_num]
fig = plt.figure()
for i, tx in enumerate([rescale, cro... | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
Create the transformed datasetApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size). | # define the data tranform
# order matters! i.e. rescaling should come before a smaller crop
data_transform = transforms.Compose([Rescale(250),
RandomCrop(224),
Normalize(),
ToTensor()])
# create the transfor... | Number of images: 3462
0 torch.Size([1, 224, 224]) torch.Size([68, 2])
1 torch.Size([1, 224, 224]) torch.Size([68, 2])
2 torch.Size([1, 224, 224]) torch.Size([68, 2])
3 torch.Size([1, 224, 224]) torch.Size([68, 2])
4 torch.Size([1, 224, 224]) torch.Size([68, 2])
| MIT | 1. Load and Visualize Data.ipynb | Buddhone/P1_Facial_Keypoints |
STEP 1: IMPORT LIBRARIES AND DATASET | import warnings
warnings.filterwarnings("ignore")
# import libraries
import pickle
import seaborn as sns
import pandas as pd # Import Pandas for data manipulation using dataframes
import numpy as np # Import Numpy for data statistical analysis
import matplotlib.pyplot as plt # Import matplotlib for data visualisation... | _____no_output_____ | MIT | traffic_sign_prediction_using_LE_NET_ARCHITECTURE.ipynb | abegpatel/Traffic-Sign-Classification-suing-LENET-Architecture |
STEP 2: IMAGE EXPLORATION¶ | i = 1001
plt.imshow(X_train[i]) # Show images are not shuffled
y_train[i] | _____no_output_____ | MIT | traffic_sign_prediction_using_LE_NET_ARCHITECTURE.ipynb | abegpatel/Traffic-Sign-Classification-suing-LENET-Architecture |
STEP 3: DATA PEPARATION | ## Shuffle the dataset
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)
X_train_gray = np.sum(X_train/3, axis=3, keepdims=True)
X_test_gray = np.sum(X_test/3, axis=3, keepdims=True)
X_validation_gray = np.sum(X_validation/3, axis=3, keepdims=True)
X_train_gray_norm = (X_train_gray - 1... | _____no_output_____ | MIT | traffic_sign_prediction_using_LE_NET_ARCHITECTURE.ipynb | abegpatel/Traffic-Sign-Classification-suing-LENET-Architecture |
STEP 4: MODEL TRAININGThe model consists of the following layers:STEP 1: THE FIRST CONVOLUTIONAL LAYER 1Input = 32x32x1Output = 28x28x6Output = (Input-filter+1)/Stride* => (32-5+1)/1=28Used a 5x5 Filter with input depth of 3 and output depth of 6Apply a RELU Activation function to the outputpooling for input, Input = 2... | # Import train_test_split from scikit library
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Dense, Flatten, Dropout
from keras.optimizers import Adam
from keras.callbacks import TensorBoard
from sklearn.model_selection import train_test_split
image_shape = X_tra... | Epoch 1/50
70/70 [==============================] - 8s 10ms/step - loss: 3.4363 - accuracy: 0.1037 - val_loss: 2.5737 - val_accuracy: 0.3120
Epoch 2/50
70/70 [==============================] - 0s 6ms/step - loss: 1.8750 - accuracy: 0.4805 - val_loss: 1.4311 - val_accuracy: 0.5537
Epoch 3/50
70/70 [=====================... | MIT | traffic_sign_prediction_using_LE_NET_ARCHITECTURE.ipynb | abegpatel/Traffic-Sign-Classification-suing-LENET-Architecture |
STEP 5: MODEL EVALUATION¶ | score = cnn_model.evaluate(X_test_gray_norm, y_test,verbose=0)
print('Test Accuracy : {:.4f}'.format(score[1]))
history.history.keys()
accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(accuracy)... | _____no_output_____ | MIT | traffic_sign_prediction_using_LE_NET_ARCHITECTURE.ipynb | abegpatel/Traffic-Sign-Classification-suing-LENET-Architecture |
Для задания 2 вытащу столбец temperature | temperature_column = weather_hourly_df.loc[:, 'temperature']
with open('files\\temperature.txt', 'w') as file:
for temp in temperature_column:
file.write(str(temp) + '\n')
path_to_passwords_json = "files\\passwords.json"
with open(path_to_passwords_json, 'r') as file:
passwords = json.load(file)
with op... | _____no_output_____ | MIT | crypto_labs/hkdf/data_analysis.ipynb | yerseg/mephi_labs |
View source on GitHub Notebook Viewer Run in Google Colab Install Earth Engine API and geemapInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://geemap.org). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jup... | # Installs geemap package
import subprocess
try:
import geemap
except ImportError:
print('Installing geemap ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap'])
import ee
import geemap | _____no_output_____ | MIT | ImageCollection/map_function.ipynb | OIEIEIO/earthengine-py-notebooks |
Create an interactive map The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. | Map = geemap.Map(center=[40,-100], zoom=4)
Map | _____no_output_____ | MIT | ImageCollection/map_function.ipynb | OIEIEIO/earthengine-py-notebooks |
Add Earth Engine Python script | # Add Earth Engine dataset
# This function adds a band representing the image timestamp.
def addTime(image):
return image.addBands(image.metadata('system:time_start'))
def conditional(image):
return ee.Algorithms.If(ee.Number(image.get('SUN_ELEVATION')).gt(40),
image,
... | _____no_output_____ | MIT | ImageCollection/map_function.ipynb | OIEIEIO/earthengine-py-notebooks |
Display Earth Engine data layers | Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.
Map | _____no_output_____ | MIT | ImageCollection/map_function.ipynb | OIEIEIO/earthengine-py-notebooks |
相関分析(pre 0 vs pre 10)ndcg_00はpre 0, ndcg_10はpre 10の結果 KCの出現数とNDCGの相関 | # 1.1
corrcoef = np.corrcoef(x=count_list, y=ndcg_00)[0][1]
print("Corr coef =", corrcoef)
ax = sns.jointplot(x=count_list, y=ndcg_00, kind='reg')
plt.xlabel("KC count")
plt.ylabel("NDCG (baseline)")
plt.show()
# 1.2
corrcoef = np.corrcoef(x=count_list, y=ndcg_10)
print("Corr coef =", corrcoef)
sns.jointplot(x=count_li... | Corr coef = [[ 1. -0.06907159]
[-0.06907159 1. ]]
| MIT | notebook/Analyze_Statics2011_NDCG.ipynb | qqhann/KnowledgeTracing |
KCの正解率とNDCGの相関(1.3)は正解率の低い問題でNDCGがやや低い傾向がみてとれる | # 1.3
sns.jointplot(x=[sum(l)/len(l) for l in count], y=ndcg_00, kind='reg')
# 1.4
sns.jointplot(x=[sum(l)/len(l) for l in count], y=ndcg_10, kind='reg') | _____no_output_____ | MIT | notebook/Analyze_Statics2011_NDCG.ipynb | qqhann/KnowledgeTracing |
出現数と正解率の関係結果考察:難しい問題はときたがらない,かんたんな問題は繰り返しがち,という傾向があるのか? | # 1.5
print(np.corrcoef(x=[len(l) for l in count], y=[sum(l)/len(l) for l in count]))
sns.jointplot(x=[len(l) for l in count], y=[sum(l)/len(l) for l in count], kind='reg') | [[1. 0.27203797]
[0.27203797 1. ]]
| MIT | notebook/Analyze_Statics2011_NDCG.ipynb | qqhann/KnowledgeTracing |
Analysis Bike Share Summary* 85% of the trips are made by users who are subscribers for the last two years (2013-08, 2015-08).* This trend has been maintained for the last couple of months (86% are subscribers).* The number of trips is variable through the days. Last couple of months follow the same trends.* Subscrib... | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np | _____no_output_____ | MIT | .ipynb_checkpoints/Bike_Share-checkpoint.ipynb | alan-toledo/bike-share-data-analysis |
Load Data | trip = pd.read_csv('trip.csv') | _____no_output_____ | MIT | .ipynb_checkpoints/Bike_Share-checkpoint.ipynb | alan-toledo/bike-share-data-analysis |
Subscription Types (Users) | trip['subscription_type'] = pd.Categorical(trip['subscription_type'])
fig, ax = plt.subplots(1, 2, figsize=(15,5))
trip['subscription_type'].value_counts().plot(kind='pie', autopct='%.2f', ax=ax[0])
stats = trip['subscription_type'].value_counts(dropna=True)
ax[1].set_ylabel('Number of trips')
ax[1].set_title('N trips'... | Some bikes are used in greater frequency.
| MIT | .ipynb_checkpoints/Bike_Share-checkpoint.ipynb | alan-toledo/bike-share-data-analysis |
Amazon SageMaker Debugger Tutorial: How to Use the Built-in Debugging Rules [Amazon SageMaker Debugger](https://docs.aws.amazon.com/sagemaker/latest/dg/train-debugger.html) is a feature that offers capability to debug training jobs of your machine learning model and identify training problems in real time. While a tra... | import sys
import IPython
install_needed = True # Set to True to upgrade
if install_needed:
print("installing deps and restarting kernel")
!{sys.executable} -m pip install -U sagemaker
!{sys.executable} -m pip install smdebug matplotlib
IPython.Application.instance().kernel.do_shutdown(True) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Check the SageMaker Python SDK and the SMDebug library versions. | import sagemaker
sagemaker.__version__
import smdebug
smdebug.__version__ | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Step 2: Create a Debugger built-in rule list object | from sagemaker.debugger import (
Rule,
rule_configs,
ProfilerRule,
ProfilerConfig,
FrameworkProfile,
DetailedProfilingConfig,
DataloaderProfilingConfig,
PythonProfilingConfig,
) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
The following code cell shows how to configure a rule object for debugging and profiling. For more information about the Debugger built-in rules, see [List of Debugger Built-in Rules](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html).The following cell demo how to configure system and framew... | profiler_config = ProfilerConfig(
system_monitor_interval_millis=500,
framework_profile_params=FrameworkProfile(
local_path="/opt/ml/output/profiler/",
detailed_profiling_config=DetailedProfilingConfig(start_step=5, num_steps=3),
dataloader_profiling_config=DataloaderProfilingConfig(star... | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Step 3: Construct a SageMaker estimatorUsing the rule object created in the previous cell, construct a SageMaker estimator. The estimator can be one of the SageMaker framework estimators, [TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.htmltensorflow-estimator), [PyTo... | import boto3
from sagemaker.tensorflow import TensorFlow
session = boto3.session.Session()
region = session.region_name
estimator = TensorFlow(
role=sagemaker.get_execution_role(),
instance_count=1,
instance_type="ml.g4dn.xlarge",
image_uri=f"763104351884.dkr.ecr.{region}.amazonaws.com/tensorflow-trai... | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Step 4: Run the training jobWith the `wait=False` option, you can proceed to the next notebook cell without waiting for the training job logs to be printed out. | estimator.fit(wait=True) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Step 5: Check training progress on Studio Debugger insights dashboard and the built-in rules evaluation status- **Option 1** - Use SageMaker Studio Debugger insights and Experiments. This is a non-coding approach.- **Option 2** - Use the following code cells. This is a code-based approach. Option 1 - Open Studio Deb... | job_name = estimator.latest_training_job.name
print("Training job name: {}".format(job_name)) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Print the training job and rule evaluation statusThe following script returns the status in real time every 15 seconds, until the secondary training status turns to one of the descriptions, `Training`, `Stopped`, `Completed`, or `Failed`. Once the training job status turns into the `Training`, you will be able to retr... | import time
client = estimator.sagemaker_session.sagemaker_client
description = client.describe_training_job(TrainingJobName=job_name)
if description["TrainingJobStatus"] != "Completed":
while description["SecondaryStatus"] not in {"Training", "Stopped", "Completed", "Failed"}:
description = client.describ... | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Step 6: Create a Debugger trial object to access the saved model parametersTo access the saved tensors by Debugger, use the `smdebug` client library to create a Debugger trial object. The following code cell sets up a `tutorial_trial` object, and waits until it finds available tensors from the default S3 bucket. | from smdebug.trials import create_trial
tutorial_trial = create_trial(estimator.latest_job_debugger_artifacts_path()) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
The Debugger trial object accesses the SageMaker estimator's Debugger artifact path, and fetches the output tensors saved for debugging. Print the default S3 bucket URI where the Debugger output tensors are stored | tutorial_trial.path | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Print the Debugger output tensor names | tutorial_trial.tensor_names() | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Print the list of steps where the tensors are saved The smdebug `ModeKeys` class provides training phase mode keys that you can use to sort training (`TRAIN`) and validation (`EVAL`) steps and their corresponding values. | from smdebug.core.modes import ModeKeys
tutorial_trial.steps(mode=ModeKeys.TRAIN)
tutorial_trial.steps(mode=ModeKeys.EVAL) | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
Plot the loss curveThe following script plots the loss and accuracy curves of training and validation loops. | trial = tutorial_trial
def get_data(trial, tname, mode):
tensor = trial.tensor(tname)
steps = tensor.steps(mode=mode)
vals = [tensor.value(s, mode=mode) for s in steps]
return steps, vals
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
def plot_tensor(trial, tensor_n... | _____no_output_____ | MIT | 04_sagemaker_debugger/tf-mnist-builtin-rule.ipynb | tom5610/amazon_sagemaker_intermediate_workshop |
This notebook was prepared by Marco Guajardo. For license visit [github](https://github.com/donnemartin/interactive-coding-challenges) Solution notebook Problem: Given a string of words, return a string with the words in reverse * [Constraits](Constraint)* [Test Cases](Test-Cases)* [Algorithm](Algorithm)* [Code](C... | def reverse_words(S):
if len(S) is 0:
return None
words = S.split()
for i in range (len(words)):
words[i] = words[i][::-1]
return " ".join(words)
%%writefile reverse_words_solution.py
from nose.tools import assert_equal
class UnitTest (object):
def testReverseWords(sel... | Success: reverse_words
| Apache-2.0 | staging/arrays_strings/reverse_words/reverse_words_solution.ipynb | sophomore99/PythonInterective |
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/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Eager Execution Run in Google Colab View source on GitHub > Note: This is an archived TF1 notebook. These are configuredto run in TF2's [compatbility mode](https://www.tensorflow.org/guide/migrate)but will run in TF1 as well. To use TF1 in Colab, use the[%tensorflow_version 1.x](https://colab.research.g... | import tensorflow.compat.v1 as tf | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Now you can run TensorFlow operations and the results will return immediately: | tf.executing_eagerly()
x = [[2.]]
m = tf.matmul(x, x)
print("hello, {}".format(m)) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Enabling eager execution changes how TensorFlow operations behave—now theyimmediately evaluate and return their values to Python. `tf.Tensor` objectsreference concrete values instead of symbolic handles to nodes in a computationalgraph. Since there isn't a computational graph to build and run later in asession, it's ea... | a = tf.constant([[1, 2],
[3, 4]])
print(a)
# Broadcasting support
b = tf.add(a, 1)
print(b)
# Operator overloading is supported
print(a * b)
# Use NumPy values
import numpy as np
c = np.multiply(a, b)
print(c)
# Obtain numpy value from a tensor:
print(a.numpy())
# => [[1 2]
# [3 4]] | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Dynamic control flowA major benefit of eager execution is that all the functionality of the hostlanguage is available while your model is executing. So, for example,it is easy to write [fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz): | def fizzbuzz(max_num):
counter = tf.constant(0)
max_num = tf.convert_to_tensor(max_num)
for num in range(1, max_num.numpy()+1):
num = tf.constant(num)
if int(num % 3) == 0 and int(num % 5) == 0:
print('FizzBuzz')
elif int(num % 3) == 0:
print('Fizz')
elif int(num % 5) == 0:
print... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
This has conditionals that depend on tensor values and it prints these valuesat runtime. Build a modelMany machine learning models are represented by composing layers. Whenusing TensorFlow with eager execution you can either write your own layers oruse a layer provided in the `tf.keras.layers` package.While you can us... | class MySimpleLayer(tf.keras.layers.Layer):
def __init__(self, output_units):
super(MySimpleLayer, self).__init__()
self.output_units = output_units
def build(self, input_shape):
# The build method gets called the first time your layer is used.
# Creating variables on build() allows you to make the... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Use `tf.keras.layers.Dense` layer instead of `MySimpleLayer` above as it hasa superset of its functionality (it can also add a bias).When composing layers into models you can use `tf.keras.Sequential` to representmodels which are a linear stack of layers. It is easy to use for basic models: | model = tf.keras.Sequential([
tf.keras.layers.Dense(10, input_shape=(784,)), # must declare input shape
tf.keras.layers.Dense(10)
]) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Alternatively, organize models in classes by inheriting from `tf.keras.Model`.This is a container for layers that is a layer itself, allowing `tf.keras.Model`objects to contain other `tf.keras.Model` objects. | class MNISTModel(tf.keras.Model):
def __init__(self):
super(MNISTModel, self).__init__()
self.dense1 = tf.keras.layers.Dense(units=10)
self.dense2 = tf.keras.layers.Dense(units=10)
def call(self, input):
"""Run the model."""
result = self.dense1(input)
result = self.dense2(result)
resul... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
It's not required to set an input shape for the `tf.keras.Model` class sincethe parameters are set the first time input is passed to the layer.`tf.keras.layers` classes create and contain their own model variables thatare tied to the lifetime of their layer objects. To share layer variables, sharetheir objects. Eager ... | w = tf.Variable([[1.0]])
with tf.GradientTape() as tape:
loss = w * w
grad = tape.gradient(loss, w)
print(grad) # => tf.Tensor([[ 2.]], shape=(1, 1), dtype=float32) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Train a modelThe following example creates a multi-layer model that classifies the standardMNIST handwritten digits. It demonstrates the optimizer and layer APIs to buildtrainable graphs in an eager execution environment. | # Fetch and format the mnist data
(mnist_images, mnist_labels), _ = tf.keras.datasets.mnist.load_data()
dataset = tf.data.Dataset.from_tensor_slices(
(tf.cast(mnist_images[...,tf.newaxis]/255, tf.float32),
tf.cast(mnist_labels,tf.int64)))
dataset = dataset.shuffle(1000).batch(32)
# Build the model
mnist_model = t... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Even without training, call the model and inspect the output in eager execution: | for images,labels in dataset.take(1):
print("Logits: ", mnist_model(images[0:1]).numpy()) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
While keras models have a builtin training loop (using the `fit` method), sometimes you need more customization. Here's an example, of a training loop implemented with eager: | optimizer = tf.train.AdamOptimizer()
loss_history = []
for (batch, (images, labels)) in enumerate(dataset.take(400)):
if batch % 10 == 0:
print('.', end='')
with tf.GradientTape() as tape:
logits = mnist_model(images, training=True)
loss_value = tf.losses.sparse_softmax_cross_entropy(labels, logits)
... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Variables and optimizers`tf.Variable` objects store mutable `tf.Tensor` values accessed duringtraining to make automatic differentiation easier. The parameters of a model canbe encapsulated in classes as variables.Better encapsulate model parameters by using `tf.Variable` with`tf.GradientTape`. For example, the automa... | class Model(tf.keras.Model):
def __init__(self):
super(Model, self).__init__()
self.W = tf.Variable(5., name='weight')
self.B = tf.Variable(10., name='bias')
def call(self, inputs):
return inputs * self.W + self.B
# A toy dataset of points around 3 * x + 2
NUM_EXAMPLES = 2000
training_inputs = tf.r... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Use objects for state during eager executionWith graph execution, program state (such as the variables) is stored in globalcollections and their lifetime is managed by the `tf.Session` object. Incontrast, during eager execution the lifetime of state objects is determined bythe lifetime of their corresponding Python ob... | if tf.test.is_gpu_available():
with tf.device("gpu:0"):
v = tf.Variable(tf.random_normal([1000, 1000]))
v = None # v no longer takes up GPU memory | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Object-based saving`tf.train.Checkpoint` can save and restore `tf.Variable`s to and fromcheckpoints: | x = tf.Variable(10.)
checkpoint = tf.train.Checkpoint(x=x)
x.assign(2.) # Assign a new value to the variables and save.
checkpoint_path = './ckpt/'
checkpoint.save('./ckpt/')
x.assign(11.) # Change the variable after saving.
# Restore values from the checkpoint
checkpoint.restore(tf.train.latest_checkpoint(checkpoi... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
To save and load models, `tf.train.Checkpoint` stores the internal state of objects,without requiring hidden variables. To record the state of a `model`,an `optimizer`, and a global step, pass them to a `tf.train.Checkpoint`: | import os
import tempfile
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16,[3,3], activation='relu'),
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(10)
])
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
checkpoint_dir = tempfile.mkdtemp()
checkpoint_prefix = os.path.join(checkpoi... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Object-oriented metrics`tf.metrics` are stored as objects. Update a metric by passing the new data tothe callable, and retrieve the result using the `tf.metrics.result` method,for example: | m = tf.keras.metrics.Mean("loss")
m(0)
m(5)
m.result() # => 2.5
m([8, 9])
m.result() # => 5.5 | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Summaries and TensorBoard[TensorBoard](https://tensorflow.org/tensorboard) is a visualization tool forunderstanding, debugging and optimizing the model training process. It usessummary events that are written while executing the program.TensorFlow 1 summaries only work in eager mode, but can be run with the `compat.v2... | from tensorflow.compat.v2 import summary
global_step = tf.train.get_or_create_global_step()
logdir = "./tb/"
writer = summary.create_file_writer(logdir)
writer.set_as_default()
for _ in range(10):
global_step.assign_add(1)
# your model code goes here
summary.scalar('global_step', global_step, step=global_step)... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Advanced automatic differentiation topics Dynamic models`tf.GradientTape` can also be used in dynamic models. This example for a[backtracking line search](https://wikipedia.org/wiki/Backtracking_line_search)algorithm looks like normal NumPy code, except there are gradients and isdifferentiable, despite the complex con... | def line_search_step(fn, init_x, rate=1.0):
with tf.GradientTape() as tape:
# Variables are automatically recorded, but manually watch a tensor
tape.watch(init_x)
value = fn(init_x)
grad = tape.gradient(value, init_x)
grad_norm = tf.reduce_sum(grad * grad)
init_value = value
while value > init_val... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Custom gradientsCustom gradients are an easy way to override gradients in eager and graphexecution. Within the forward function, define the gradient with respect to theinputs, outputs, or intermediate results. For example, here's an easy way to clipthe norm of the gradients in the backward pass: | @tf.custom_gradient
def clip_gradient_by_norm(x, norm):
y = tf.identity(x)
def grad_fn(dresult):
return [tf.clip_by_norm(dresult, norm), None]
return y, grad_fn | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Custom gradients are commonly used to provide a numerically stable gradient for asequence of operations: | def log1pexp(x):
return tf.log(1 + tf.exp(x))
class Grad(object):
def __init__(self, f):
self.f = f
def __call__(self, x):
x = tf.convert_to_tensor(x)
with tf.GradientTape() as tape:
tape.watch(x)
r = self.f(x)
g = tape.gradient(r, x)
return g
grad_log1pexp = Grad(log1pexp)
# The... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Here, the `log1pexp` function can be analytically simplified with a customgradient. The implementation below reuses the value for `tf.exp(x)` that iscomputed during the forward pass—making it more efficient by eliminatingredundant calculations: | @tf.custom_gradient
def log1pexp(x):
e = tf.exp(x)
def grad(dy):
return dy * (1 - 1 / (1 + e))
return tf.log(1 + e), grad
grad_log1pexp = Grad(log1pexp)
# As before, the gradient computation works fine at x = 0.
grad_log1pexp(0.).numpy()
# And the gradient computation also works at x = 100.
grad_log1pexp(100... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
PerformanceComputation is automatically offloaded to GPUs during eager execution. If youwant control over where a computation runs you can enclose it in a`tf.device('/gpu:0')` block (or the CPU equivalent): | import time
def measure(x, steps):
# TensorFlow initializes a GPU the first time it's used, exclude from timing.
tf.matmul(x, x)
start = time.time()
for i in range(steps):
x = tf.matmul(x, x)
# tf.matmul can return before completing the matrix multiplication
# (e.g., can return after enqueing the opera... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
A `tf.Tensor` object can be copied to a different device to execute itsoperations: | if tf.test.is_gpu_available():
x = tf.random_normal([10, 10])
x_gpu0 = x.gpu()
x_cpu = x.cpu()
_ = tf.matmul(x_cpu, x_cpu) # Runs on CPU
_ = tf.matmul(x_gpu0, x_gpu0) # Runs on GPU:0 | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
BenchmarksFor compute-heavy models, such as[ResNet50](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/resnet50)training on a GPU, eager execution performance is comparable to graph execution.But this gap grows larger for models with less computation and there is work tobe ... | def my_py_func(x):
x = tf.matmul(x, x) # You can use tf ops
print(x) # but it's eager!
return x
with tf.Session() as sess:
x = tf.placeholder(dtype=tf.float32)
# Call eager function in graph!
pf = tf.py_func(my_py_func, [x], tf.float32)
sess.run(pf, feed_dict={x: [[2.0]]}) # [[4.0]] | _____no_output_____ | Apache-2.0 | site/en/r1/guide/eager.ipynb | PRUBHTEJ/docs-1 |
Interactive Variant AnnotationThe following query retrieves variants from [DeepVariant-called Platinum Genomes](http://googlegenomics.readthedocs.io/en/latest/use_cases/discover_public_data/platinum_genomes_deepvariant.html) and interactively JOINs them with [ClinVar](http://googlegenomics.readthedocs.io/en/latest/use... | %%bq query
#standardSQL
--
-- Return variants for sample NA12878 that are:
-- annotated as 'pathogenic' or 'other' in ClinVar
-- with observed population frequency less than 5%
--
WITH sample_variants AS (
SELECT
-- Remove the 'chr' prefix from the reference name.
REGEXP_EXTRACT(reference_name... | _____no_output_____ | Apache-2.0 | interactive/InteractiveVariantAnnotation.ipynb | bashir2/variant-annotation |
Dealing with compound data setUsing dtypes one can detect the names for the dtype and then copy into an array and convert to np.strThen pandas DataFrame can parse those properly as a table | import pandas as pd
import numpy as np
import h5py
h5 = h5py.File('../../tests/historical_v82.h5')
x=h5.get('/hydro/geometry/reservoir_node_connect') | _____no_output_____ | MIT | docs/html/notebooks/h5_compound_dataset_as_dataframe.ipynb | sainjacobs/pydsm |
See below on how to use dtype on returned array to see the names | x[0].dtype.names | _____no_output_____ | MIT | docs/html/notebooks/h5_compound_dataset_as_dataframe.ipynb | sainjacobs/pydsm |
Now the names can be used to get the value for that dtype | x[0]['res_name'] | _____no_output_____ | MIT | docs/html/notebooks/h5_compound_dataset_as_dataframe.ipynb | sainjacobs/pydsm |
Using generative expressions to get the values as arrays of arrays with everything converted to strings | pd.DataFrame([[v[name].astype(np.str) for name in v.dtype.names] for v in x])
| _____no_output_____ | MIT | docs/html/notebooks/h5_compound_dataset_as_dataframe.ipynb | sainjacobs/pydsm |
4.3.4 抽出した文章群から日本語極性辞書にマッチする単語を特定しトーンを算出抽出した文章群から乾・鈴木(2008)で公開された日本語評価極性辞書を用いて、マッチする単語を特定しトーンを算出する。ここでは、osetiと呼ばれる日本語評価極性辞書を用いて極性の判定を行うPythonのライブラリを用いた。 | import glob
def call_sample_dir_name(initial_name):
if initial_name == "a":
return "AfterSample"
elif initial_name == "t":
return "TransitionPeriodSample"
else:
return "BeforeSample"
def call_csv_files(sample_dir_name="AfterSample", data_frame_spec=None, industry_spec=None):
... | _____no_output_____ | MIT | src/4AnalysingText/analyzing_text.ipynb | Densuke-fitness/MDandAAnalysisFlow |
Publications markdown generator for academicpagesTakes a TSV of publications with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.htm... | !cat publications.tsv | pub_date title venue excerpt citation url_slug paper_url
2012 The effect of surface wave propagation on neural responses to vibration in primate glabrous skin. PloS one Manfredi LR, Baker AT, Elias DO, Dammann III JF, Zielinski MC, Polashock VS, Bensmaia SJ. The effect of surface wave propagation on neural responses ... | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
Import pandasWe are using the very handy pandas library for dataframes. | import pandas as pd | _____no_output_____ | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
Import TSVPandas makes this easy with the read_csv function. We are using a TSV, so we specify the separator as a tab, or `\t`.I found it important to put this data in a tab-separated values format, because there are a lot of commas in this kind of data and comma-separated values can get messed up. However, you can mo... | publications = pd.read_csv("publications.tsv", sep="\t", header=0)
publications
| _____no_output_____ | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
Escape special charactersYAML is very picky about how it takes a valid string, so we are replacing single and double quotes (and ampersands) with their HTML encoded equivilents. This makes them look not so readable in raw format, but they are parsed and rendered nicely. | html_escape_table = {
"&": "&",
'"': """,
"'": "'"
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text) | _____no_output_____ | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
Creating the markdown filesThis is where the heavy lifting is done. This loops through all the rows in the TSV dataframe, then starts to concatentate a big string (```md```) that contains the markdown for each type. It does the YAML metadata first, then does the description for the individual page. | import os
for row, item in publications.iterrows():
md_filename = str(item.pub_date) + "-" + item.url_slug + ".md"
html_filename = str(item.pub_date) + "-" + item.url_slug
year = item.pub_date[:4]
## YAML variables
md = "---\ntitle: \"" + item.title + '"\n'
md += """collect... | _____no_output_____ | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
These files are in the publications directory, one directory below where we're working from. | !ls ../_publications/
!cat ../_publications/2009-10-01-paper-title-number-1.md | ---
title: "Paper Title Number 1"
collection: publications
permalink: /publication/2009-10-01-paper-title-number-1
excerpt: 'This paper is about the number 1. The number 2 is left for future work.'
date: 2009-10-01
venue: 'Journal 1'
paperurl: 'http://academicpages.github.io/files/paper1.pdf'
citation: 'Your Na... | MIT | markdown_generator/publications.ipynb | mczielinski/mczielinski.github.io |
**[Deep Learning Course Home Page](https://www.kaggle.com/learn/deep-learning)**--- IntroductionYou've seen how to build a model from scratch to identify handwritten digits. You'll now build a model to identify different types of clothing. To make models that train quickly, we'll work with very small (low-resolution... | import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow import keras
img_rows, img_cols = 28, 28
num_classes = 10
def prep_data(raw):
y = raw[:, 0]
out_y = keras.utils.to_categorical(y, num_classes)
x = raw[:,1:]
num_images = raw.shape[0]
out_x = x.reshape(num_... | Using TensorFlow version 2.1.0
Setup Complete
| MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
1) Start the modelCreate a `Sequential` model called `fashion_model`. Don't add layers yet. | from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D
# Your Code Here
fashion_model = Sequential()
q_1.check()
#q_1.solution() | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
2) Add the first layerAdd the first `Conv2D` layer to `fashion_model`. It should have 12 filters, a kernel_size of 3 and the `relu` activation function. The first layer always requires that you specify the `input_shape`. We have saved the number of rows and columns to the variables `img_rows` and `img_cols` respectiv... | # Your code here
fashion_model.add(Conv2D(12, kernel_size=(3, 3),
activation='relu',
input_shape=(img_rows, img_cols, 1)))
q_2.check()
# q_2.hint()
#q_2.solution() | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
3) Add the remaining layers1. Add 2 more convolutional (`Conv2D layers`) with 20 filters each, 'relu' activation, and a kernel size of 3. Follow that with a `Flatten` layer, and then a `Dense` layer with 100 neurons. 2. Add your prediction layer to `fashion_model`. This is a `Dense` layer. We alrady have a variable ... | # Your code here
fashion_model.add(Conv2D(20, kernel_size=(3, 3), activation='relu'))
fashion_model.add(Conv2D(20, kernel_size=(3, 3), activation='relu'))
fashion_model.add(Flatten())
fashion_model.add(Dense(100, activation='relu'))
fashion_model.add(Dense(num_classes, activation='softmax'))
q_3.check()
# q_3.solution... | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
4) Compile Your ModelCompile fashion_model with the `compile` method. Specify the following arguments:1. `loss = "categorical_crossentropy"`2. `optimizer = 'adam'`3. `metrics = ['accuracy']` | # Your code to compile the model in this cell
fashion_model.compile(loss=keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy'])
q_4.check()
# q_4.solution() | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
5) Fit The ModelRun the command `fashion_model.fit`. The arguments you will use are1. The data used to fit the model. First comes the data holding the images, and second is the data with the class labels to be predicted. Look at the first code cell (which was supplied to you) where we called `prep_data` to find the va... | # Your code to fit the model here
fashion_model.fit(x, y, batch_size = 100, epochs = 4, validation_split = 0.2)
q_5.check()
#q_5.solution() | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.