markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Comparamos resultados:
cnn_pred = CNN.predict(X_test, verbose=1) dfn_pred = DFN.predict(X_test.reshape((X_test.shape[0], np.prod(X_test.shape[1:]))), verbose=1) cnn_pred = np.array(list(map(np.argmax, cnn_pred))) dfn_pred = np.array(list(map(np.argmax, dfn_pred))) y_pred = np.array(list(map(np.argmax, y_test))) util.plotconfusion(util.g...
src/Keras Tutorial.ipynb
MLIME/12aMostra
gpl-3.0
Vamos observar alguns exemplos mal classificados:
cnn_missed = cnn_pred != y_pred dfn_missed = dfn_pred != y_pred cnn_and_dfn_missed = np.logical_and(dfn_missed, cnn_missed) util.plot_missed_examples(X_test, y_pred, dfn_missed, dfn_pred) util.plot_missed_examples(X_test, y_pred, cnn_missed, cnn_pred) util.plot_missed_examples(X_test, y_pred, cnn_and_dfn_missed)
src/Keras Tutorial.ipynb
MLIME/12aMostra
gpl-3.0
Question 0 (Example) What is the first country in df? This function should return a Series.
# You should write your whole answer within the function provided. The autograder will call # this function and compare the return value against the correct solution value def answer_zero(): # This function returns the row for Afghanistan, which is a Series object. The assignment # question description will tel...
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 1 Which country has won the most gold medals in summer games? This function should return a single string value.
def answer_one(): answer = df.sort(['Gold'], ascending = False) return answer.index[0] answer_one()
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 2 Which country had the biggest difference between their summer and winter gold medal counts? This function should return a single string value.
def answer_two(): df['Gold_difference'] = df['Gold'] - df['Gold.1'] answer = df.sort(['Gold_difference'], ascending = False) return answer.index[0] answer_two()
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 3 Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count? $$\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$ Only include countries that have won at least 1 gold in both summer and winter. This function should return ...
def answer_three(): only_gold = df[(df['Gold.1'] > 0) & (df['Gold'] > 0)] only_gold['big_difference'] = (only_gold['Gold'] - only_gold['Gold.1']) / only_gold['Gold.2'] answer = only_gold.sort(['big_difference'], ascending = False) return answer.index[0] answer_three()
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 4 Write a function that creates a Series called "Points" which is a weighted value where each gold medal (Gold.2) counts for 3 points, silver medals (Silver.2) for 2 points, and bronze medals (Bronze.2) for 1 point. The function should return only the column (a Series object) which you created. This function s...
def answer_four(): df['Points'] = (df['Gold.2'] * 3) + (df['Silver.2'] * 2) + (df['Bronze.2'] * 1) return df['Points'] answer_four()
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Part 2 For the next set of questions, we will be using census data from the United States Census Bureau. Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. See this document for a description of th...
census_df = pd.read_csv('census.csv') census_df def answer_five(): newdf = census_df.groupby(['STNAME']).count() answer = newdf.sort(['CTYNAME'], ascending = False) return answer.index[0] answer_five()
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 6 Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)? Use CENSUS2010POP. This function should return a list of string values.
def answer_six(): ctydf = census_df[census_df['SUMLEV'] == 50] ctydfs = ctydf.sort(['CENSUS2010POP'], ascending = False) ctydfst3 = ctydfs.groupby('STNAME').head(3) ldf = ctydfst3.groupby(['STNAME']).sum() answer = ldf.sort(['CENSUS2010POP'], ascending = False) return answer.index[0:3].tolist() ...
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 7 Which county has had the largest absolute change in population within the period 2010-2015? (Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to consider all six columns.) e.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its la...
def answer_seven(): return "YOUR ANSWER HERE"
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Question 8 In this datafile, the United States is broken up into four regions using the "REGION" column. Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014. This function should return a 5x2 DataFr...
def answer_eight(): ctydf = census_df[(census_df['SUMLEV'] == 50) & (census_df['REGION'] < 3)] ctydfwas = ctydf.loc[(ctydf['CTYNAME'] == 'Washington County') & (ctydf['POPESTIMATE2015'] > ctydf['POPESTIMATE2014'])] columns_to_keep = ['STNAME', 'CTYNAME'] ansdf = ctydfwas[columns_to_ke...
Data_Science_Course/Michigan Data Analysis Course/0 Introduction to Data Science in Python/Week2/Assignment+2 (1).ipynb
Z0m6ie/Zombie_Code
mit
Problem 1: Understanding the Data For this problem set, we will use the Galaxy10 dataset made available via the astroNN module. This dataset is made up of 17736 images of galaxies which have been labelled by hand. See this link for more information. First we will visualize our data. Problem 1a Show one example of each...
from astroNN.datasets import load_galaxy10 images, labels_original = load_galaxy10() from astroNN.datasets.galaxy10 import galaxy10cls_lookup %matplotlib inline # Plot an example image from each class # First, find an example of each class uclasses, counts = np.unique(labels_original,return_counts=True) print(len(lab...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 2b Make a histogram showing the fraction of each class Keep only the top two classes (i.e., the classes with the most galaxies)
plt.hist(labels_original) plt.xlabel('Class Label') plt.show() #Only work with 1 and 2 gind = np.where((labels_original==1) | (labels_original==2)) images_top_two = images[gind] labels_top_two = labels_original[gind]
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
This next block of code converts the data to a format which is more compatible with our neural network.
import torch.nn.functional as F torch.set_default_dtype(torch.float) labels_top_two_one_hot = F.one_hot(torch.tensor(labels_top_two - np.min(labels_top_two)).long(), num_classes=2) images_top_two = torch.tensor(images_top_two).float() labels_top_two_one_hot = labels_top_two_one_hot.float() # we're going to flatten the ...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 2c Split the data into a training and test set (66/33 split) using the train_test_split function from sklearn
from sklearn.model_selection import train_test_split images_train, images_test, labels_train, labels_test = train_test_split( images_top_two_flat, labels_top_two_one_hot, test_size=0.33, random_state=42) np.shape(images_train)
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
The next cell will outline how one can make a MLP with pytorch. Problem 3a Talk to a partner about how this code works, line by line. Add another hidden layer which is the same size as the first hidden layer.
class MLP(torch.nn.Module): # this defines the model def __init__(self, input_size, hidden_size): super(MLP, self).__init__() print(input_size,hidden_size) self.input_size = input_size self.hidden_size = hidden_size self.hiddenlayer = torch.nn.L...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
The next block of code will show how one can train the model for 100 epochs. Note that we use the binary cross-entropy as our objective function and stochastic gradient descent as our optimization method. Problem 3b Edit the code so that the function plots the loss for the training and test loss for each epoch.
# train the model def train_model(training_data,training_labels, test_data,test_labels, model): # define the optimization criterion = torch.nn.BCELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.007,momentum=0.9) for epoch in range(100): # clear the gradient optimizer.zero_grad() # comput...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
The next block trains the code, assuming a hidden layer size of 100 neurons. Problem 3c Change the learning rate lr to minimize the cross entropy score
model = MLP(np.shape(images_train[0])[0],50) train_model(images_train, labels_train, images_test, labels_test, model)
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Write a function called evaluate_model which takes the image data, labels and model as input, and the accuracy as output. you can use the accuracy_score function.
# evaluate the model def evaluate_model(data,labels, model): yhat = model(data) yhat = yhat.detach().numpy() best_class = np.argmax(yhat,axis=1) acc = accuracy_score(best_class,np.argmax(labels,axis=1)) return(acc) # evaluate the model acc = evaluate_model(images_test,labels_test, model) print('Accuracy: %.3f...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 3d make a confusion matrix for the test set
yhat = model(images_test) yhat = yhat.detach().numpy() best_class = np.argmax(yhat,axis=1) truth = np.argmax(labels_test,axis=1) cm = confusion_matrix(truth,best_class) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot() plt.show()
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Challenge Problem Add a third class to your classifier and begin accounting for uneven classes. There are several steps to this: Edit the neural network to output 3 classes Change the criterion to a custom criterion function, such that the entropy of each class is weighted by the inverse fraction of each class size (e...
class MLP_new(torch.nn.Module): # this defines the model def __init__(self, input_size, hidden_size): super(MLP_new, self).__init__() print(input_size,hidden_size) self.input_size = input_size self.hidden_size = hidden_size self.hiddenlayer = to...
Sessions/Session14/Day2/DeeplearningSolutions.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Unit Test The following unit test is expected to fail until you solve the challenge.
# %load test_compress.py from nose.tools import assert_equal class TestCompress(object): def test_compress(self, func): assert_equal(func(None), None) assert_equal(func(''), '') assert_equal(func('AABBCC'), 'AABBCC') assert_equal(func('AAABCCDDDD'), 'A3B1C2D4') print('Succ...
wk0/notebooks/challenges/compress/.ipynb_checkpoints/compress_challenge-checkpoint.ipynb
saashimi/code_guild
mit
TensorFlow Distributions の形状を理解する <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/probability/examples/Understanding_TensorFlow_Distributions_Shapes"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_bl...
import collections import tensorflow as tf tf.compat.v2.enable_v2_behavior() import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
基礎 TensorFlow Distributions の形状には関連する 3 つの重要な概念があります。 イベントの形状は、分布からの 1 つの抽出の形状を表します。抽出は次元間で依存する場合があります。スカラー分布の場合、イベントの形状は [] です。5 次元の MultivariateNormal の場合、イベントの形状は [5] です。 バッチの形状は、独立した、同一に分布されていない抽出である「バッチ」の分布を表します。 サンプルの形状は、 分布ファミリからの独立した、同一に分布されたバッチの抽出を表します。 イベントの形状とバッチの形状は Distribution オブジェクトのプロパティですが、サンプルの形状は s...
def describe_distributions(distributions): print('\n'.join([str(d) for d in distributions]))
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
このセクションでは、スカラー分布(イベントの形状が [] の分布)について説明します。典型的な例は、rate で指定されたポアソン分布です。
poisson_distributions = [ tfd.Poisson(rate=1., name='One Poisson Scalar Batch'), tfd.Poisson(rate=[1., 10., 100.], name='Three Poissons'), tfd.Poisson(rate=[[1., 10., 100.,], [2., 20., 200.]], name='Two-by-Three Poissons'), tfd.Poisson(rate=[1.], name='One Poisson Vector Batch'), tfd...
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
ポアソン分布はスカラー分布であるため、そのイベントの形状は常に [] です。より多くのレートを指定すると、これらはバッチ形式で表示されます。例の最後のペアは興味深いものです。レートは 1 つだけですが、そのレートは空でない形状の numpy 配列に埋め込まれているため、その形状がバッチ形状になります。 標準の正規分布もスカラーです。イベントの形状は、ポアソンの場合と同じように [] ですが、ブロードキャストの最初の例で見ていきます。正規分布は、loc および scale パラメーターを使用して指定されます。
normal_distributions = [ tfd.Normal(loc=0., scale=1., name='Standard'), tfd.Normal(loc=[0.], scale=1., name='Standard Vector Batch'), tfd.Normal(loc=[0., 1., 2., 3.], scale=1., name='Different Locs'), tfd.Normal(loc=[0., 1., 2., 3.], scale=[[1.], [5.]], name='Broadcasting Scale') ] descr...
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
上記の Broadcasting Scale 分布は興味深い例です。loc パラメーターは [4] の形状、scale パラメーターは [2, 1] の形状をもちます。Numpy ブロードキャストルールを使用すると、バッチ形状は [2, 4] になります。 "Broadcasting Scale" 分布を定義するための同等の(ただし、あまりエレガントではなく、推奨されない)方法は次のとおりです。
describe_distributions( [tfd.Normal(loc=[[0., 1., 2., 3], [0., 1., 2., 3.]], scale=[[1., 1., 1., 1.], [5., 5., 5., 5.]])])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
以上のようにブロードキャストの表記は頭痛やバグの原因にもなりますが便利です。 スカラー分布のサンプリング 分布で実行できる主なことは sample と log_prob の 2 つです。まず、サンプリングについて見ていきましょう。基本的なルールは、分布からサンプリングする場合、結果のテンソルは形状 [sample_shape, batch_shape, event_shape] になります。batch_shape と event_shape は Distribution オブジェクトにより提供され、sample_shape は、sample の呼び出しにより提供されます。スカラー分布の場合、event_shape = [] であるた...
def describe_sample_tensor_shape(sample_shape, distribution): print('Sample shape:', sample_shape) print('Returned sample tensor shape:', distribution.sample(sample_shape).shape) def describe_sample_tensor_shapes(distributions, sample_shapes): started = False for distribution in distributions...
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
sample についての説明は以上です。返されたサンプルテンソルの形状は [sample_shape, batch_shape, event_shape] です。 スカラー分布の log_prob の計算 次に、log_prob を見てみましょう。これは少し注意する必要があります。log_prob は、分布の log_prob を計算する場所を表す(空でない)テンソルを入力として受け取ります。最も単純なケースでは、このテンソルは [sample_shape, batch_shape, event_shape] の形式になります。batch_shape と event_shape は 分布のバッチおよびイベントの形状に一致します。スカ...
three_poissons = tfd.Poisson(rate=[1., 10., 100.], name='Three Poissons') three_poissons three_poissons.log_prob([[1., 10., 100.], [100., 10., 1]]) # sample_shape is [2]. three_poissons.log_prob([[[[1., 10., 100.], [100., 10., 1.]]]]) # sample_shape is [1, 1, 2].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
最初の例では、入力と出力の形状が [2, 3] であり、2 番目の例では形状が [1, 1, 2, 3] であることに注意してください。 ブロードキャストがない場合はそれだけです。ブロードキャストを考慮する場合のルールは次のとおりです。これは一般的な説明であり、スカラー分布は簡略化されていることに注意してください。 n = len(batch_shape) + len(event_shape) を定義します。(スカラー分布の場合は、len(event_shape)=0。) 入力テンソル t の次元が n 未満の場合、正確に n 次元になるまで、左側にサイズ 1 の次元を追加して形状をパッディングします。 t' の右端の次元 n を...
three_poissons.log_prob([10.])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
テンソル [10.] (形状 [1])は 3 つのbatch_shape でブロードキャストされるため、値 10 での 3 つのポワソンの対数確率をすべて評価します。
three_poissons.log_prob([[[1.], [10.]], [[100.], [1000.]]])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
上記の例では、入力テンソルの形状は [2, 2, 1] ですが、分布オブジェクトの形状は 3 です。したがって、[2, 2] サンプル次元のそれぞれについて、提供された単一の値は、3 つのポワソンのそれぞれにブロードキャストします。 これは役に立つ考え方です。three_poissons には batch_shape = [2, 3] があるため、log_prob の呼び出しには最後の次元が 1 または 3 のテンソルが必要です。それ以外はエラーです。(numpy ブロードキャストルールは、スカラーの特殊なケースを、形状 [1] のテンソルと完全に同等であるものとして扱います。) では、batch_shape = [2, 3] を使...
poisson_2_by_3 = tfd.Poisson( rate=[[1., 10., 100.,], [2., 20., 200.]], name='Two-by-Three Poissons') poisson_2_by_3.log_prob(1.) poisson_2_by_3.log_prob([1.]) # Exactly equivalent to above, demonstrating the scalar special case. poisson_2_by_3.log_prob([[1., 1., 1.], [1., 1., 1.]]) # Another way to write ...
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
上記の例では、バッチを介したブロードキャストを見ていきましたが、サンプルの形状は空でした。値のコレクションがあり、バッチの各ポイントで各値の対数確率を取得する場合は、以下のように手動で実行できます。
poisson_2_by_3.log_prob([[[1., 1., 1.], [1., 1., 1.]], [[2., 2., 2.], [2., 2., 2.]]]) # Input shape [2, 2, 3].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
または、ブロードキャストに最後のバッチ次元を処理させることもできます。
poisson_2_by_3.log_prob([[[1.], [1.]], [[2.], [2.]]]) # Input shape [2, 2, 1].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
また、やや不自然ですがブロードキャストに最初のバッチ次元のみを処理させることもできます。
poisson_2_by_3.log_prob([[[1., 1., 1.]], [[2., 2., 2.]]]) # Input shape [2, 1, 3].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
または、ブロードキャストに両方のバッチ次元を処理させることもできます。
poisson_2_by_3.log_prob([[[1.]], [[2.]]]) # Input shape [2, 1, 1].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
上記は、必要な値が 2 つしかない場合は問題ありませんでした。しかし、すべてのバッチポイントで評価する値のリストが長い場合は、次の表記を使用します。形状の右側にサイズ 1 の余分な次元を追加すると、非常に便利です。
poisson_2_by_3.log_prob(tf.constant([1., 2.])[..., tf.newaxis, tf.newaxis])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
これはストライドスライス表記のインスタンスであり、知っておく価値があります。 完全を期すために three_poissons に戻ると、同じ例は次のようになります。
three_poissons.log_prob([[1.], [10.], [50.], [100.]]) three_poissons.log_prob(tf.constant([1., 10., 50., 100.])[..., tf.newaxis]) # Equivalent to above.
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
多変量分布 ここでは、空でないイベント形状を持つ多変量分布を見ていきます。まず、多項分布を見てみましょう。
multinomial_distributions = [ # Multinomial is a vector-valued distribution: if we have k classes, # an individual sample from the distribution has k values in it, so the # event_shape is `[k]`. tfd.Multinomial(total_count=100., probs=[.5, .4, .1], name='One Multinomial'), tfd.Mu...
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
最後の 3 つの例では、batch_shape は常に [2] でしたが、ブロードキャストを使用して、共有する total_count または共有する probs 使用できます(または、使用しないこともできます)。内部では同じ形状になるようにブロードキャストされるためです。 既知の事柄を考慮すると、サンプリングは簡単です。
describe_sample_tensor_shapes(multinomial_distributions, sample_shapes)
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
対数確率の計算も同様に簡単です。対角多変量正規分布の例を見てみましょう。(カウントと確率の制約により、ブロードキャストは許容できない値を生成することが多いため、多項分布はブロードキャストにあまり適していません。)平均は同じですがスケール(標準偏差)が異なる 2 つの 3 次元分布のバッチを使用します。
two_multivariate_normals = tfd.MultivariateNormalDiag(loc=[1., 2., 3.], scale_identity_multiplier=[1., 2.]) two_multivariate_normals
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
(スケールが ID の倍数である分布を使用したが、これは制限ではないことに注意してください。scale_identity_multiplier の代わりに scale を渡すことができます。) 次に、各バッチポイントの平均とシフトされた平均での対数確率を評価します。
two_multivariate_normals.log_prob([[[1., 2., 3.]], [[3., 4., 5.]]]) # Input has shape [2,1,3].
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
まったく同じように、[https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/strided-slice](ストライドスライス表記)を使用して、定数の中央に追加の形状 = 1 次元を挿入できます。
two_multivariate_normals.log_prob( tf.constant([[1., 2., 3.], [3., 4., 5.]])[:, tf.newaxis, :]) # Equivalent to above.
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
一方、余分な次元を追加しない場合は、[1., 2., 3.] を最初のバッチポイントに渡し、[3., 4., 5.] を 2 番目のバッチポイントに渡します。
two_multivariate_normals.log_prob(tf.constant([[1., 2., 3.], [3., 4., 5.]]))
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
形状変換テクニック Reshape Bijector Reshape Bijector を使用すると、分布の event_shape の形状を変換できます。以下に例を示します。
six_way_multinomial = tfd.Multinomial(total_count=1000., probs=[.3, .25, .2, .15, .08, .02]) six_way_multinomial
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
[6] のイベント形状を持つ多項分布を作成しました。Reshape Bijector を使用すると、これを [2, 3] のイベント形状を持つ分布として扱うことができます。 Bijector は、${\mathbb R}^n$ の開集合上の微分可能な 1 対 1 の関数を表します。Bijectors は、TransformedDistribution と組み合わせて使用されます。これは、基本分布 $p(x)$ および$Y = g(X)$ を表す Bijector に関して分布 $p(y)$ をモデル化します。では、実際に見てみましょう。
transformed_multinomial = tfd.TransformedDistribution( distribution=six_way_multinomial, bijector=tfb.Reshape(event_shape_out=[2, 3])) transformed_multinomial six_way_multinomial.log_prob([500., 100., 100., 150., 100., 50.]) transformed_multinomial.log_prob([[500., 100., 100.], [150., 100., 50.]])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
これは、Reshape Bijector が実行できる唯一のことです。イベント次元をバッチ次元に、またはバッチ次元をイベント次元に変換することはできません。 Independent 分布 Independent 分布は、独立した、必ずしも同一ではない分布(バッチ)のコレクションを単一の分布として扱うために使用されます。より簡潔に言えば、Independent を使用すると、batch_shape の次元を event_shape の次元に変換できます。次に例を示します。
two_by_five_bernoulli = tfd.Bernoulli( probs=[[.05, .1, .15, .2, .25], [.3, .35, .4, .45, .5]], name="Two By Five Bernoulli") two_by_five_bernoulli
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
これは、表の確率が関連付けられた 2x5 のコインの配列として考えることができます。特定の任意の 1 と 0 のセットの確率を評価します。
pattern = [[1., 0., 0., 1., 0.], [0., 0., 1., 1., 1.]] two_by_five_bernoulli.log_prob(pattern)
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
Independent を使用すると、これを 2 つの異なる「5 つのベルヌーイのセット」に変換できます。これは、特定のパターンで出現するコイントスの「行」を単一の結果と見なす場合に役立ちます。
two_sets_of_five = tfd.Independent( distribution=two_by_five_bernoulli, reinterpreted_batch_ndims=1, name="Two Sets Of Five") two_sets_of_five
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
数学的には、5 つの「セット」ごとの対数確率を計算しています。セット内の 5 つの「独立した」コイントスの対数確率を合計するため、分布は「independent」と呼ばれます。
two_sets_of_five.log_prob(pattern)
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
さらに、Independent を使用して、個々のイベントが 2x5 のベルヌーイのセットである分布を作成できます。
one_set_of_two_by_five = tfd.Independent( distribution=two_by_five_bernoulli, reinterpreted_batch_ndims=2, name="One Set Of Two By Five") one_set_of_two_by_five.log_prob(pattern)
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
sample の観点では、Independent を使用しても何も変更されないことに注意してください。
describe_sample_tensor_shapes( [two_by_five_bernoulli, two_sets_of_five, one_set_of_two_by_five], [[3, 5]])
site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb
tensorflow/docs-l10n
apache-2.0
Model Complexity, Overfitting and Underfitting
from plots import plot_kneighbors_regularization plot_kneighbors_regularization()
day3-machine-learning/06 - Model Complexity.ipynb
lvrzhn/AstroHackWeek2015
gpl-2.0
Validation Curves
from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier from sklearn.learning_curve import validation_curve digits = load_digits() X, y = digits.data, digits.target model = RandomForestClassifier(n_estimators=20) param_range = range(1, 13) training_scores, validation_scores = vali...
day3-machine-learning/06 - Model Complexity.ipynb
lvrzhn/AstroHackWeek2015
gpl-2.0
Exercise Plot the validation curve on the digit dataset for: * a LinearSVC with a logarithmic range of regularization parameters C. * KNeighborsClassifier with a linear range of neighbors k. What do you expect them to look like? How do they actually look like?
# %load solutions/validation_curve.py
day3-machine-learning/06 - Model Complexity.ipynb
lvrzhn/AstroHackWeek2015
gpl-2.0
Our test class inherits the default configuration DefaultConfig, while also declaring some additional attributes that are specific to the Person Type/Role Annotation in Video task: inputColumns: list of input columns from the .csv file with the input data outputColumns: list of output columns from the .csv file with t...
import nltk nltk.download('stopwords') nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('wordnet') from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet from autocorrect import spell def correct_words(keywords, separator): keywords...
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The complete configuration class is declared below:
class TestConfig(DefaultConfig): inputColumns = ["videolocation", "subtitles", "imagetags", "subtitletags"] outputColumns = ["keywords"] # processing of a closed task open_ended_task = True annotation_vector = [] def processJudgments(self, judgments): # pre-process output to ma...
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Pre-processing the input data After declaring the configuration of our input file, we are ready to pre-process the crowd data:
data, config = crowdtruth.load( file = "../data/person-video-free-input.csv", config = TestConfig() ) data['judgments'].head()
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
results is a dict object that contains the quality metrics for the video fragments, annotations and crowd workers. The video fragment metrics are stored in results["units"]:
results["units"].head()
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The uqs column in results["units"] contains the video fragment quality scores, capturing the overall workers agreement over each video fragment. Here we plot its histogram:
import matplotlib.pyplot as plt %matplotlib inline plt.hist(results["units"]["uqs"]) plt.xlabel("Video Fragment Quality Score") plt.ylabel("Video Fragment")
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The unit_annotation_score column in results["units"] contains the video fragment-annotation scores, capturing the likelihood that an annotation is expressed in a video fragment. For each video fragment, we store a dictionary mapping each annotation to its video fragment-relation score.
results["units"]["unit_annotation_score"].head()
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The worker metrics are stored in results["workers"]:
results["workers"].head()
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The wqs columns in results["workers"] contains the worker quality scores, capturing the overall agreement between one worker and all the other workers.
plt.hist(results["workers"]["wqs"]) plt.xlabel("Worker Quality Score") plt.ylabel("Workers")
tutorial/notebooks/Free Input Task - Person Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Then, read the (sample) input tables for blocking purposes.
# Get the datasets directory datasets_dir = em.get_install_path() + os.sep + 'datasets' # Get the paths of the input tables path_A = datasets_dir + os.sep + 'person_table_A.csv' path_B = datasets_dir + os.sep + 'person_table_B.csv' # Read the CSV files and set 'ID' as the key attribute A = em.read_csv_metadata(path_A...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Ways To Do Overlap Blocking There are three different ways to do overlap blocking: Block two tables to produce a candidate set of tuple pairs. Block a candidate set of tuple pairs to typically produce a reduced candidate set of tuple pairs. Block two tuples to check if a tuple pair would get blocked. Block Tables to ...
# Instantiate overlap blocker object ob = em.OverlapBlocker()
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
For the given two tables, we will assume that two persons with no sufficient overlap between their addresses do not refer to the same real world person. So, we apply overlap blocking on address. Specifically, we tokenize the address by word and include the tuple pairs if the addresses have at least 3 overlapping tokens...
# Specify the tokenization to be 'word' level and set overlap_size to be 3. C1 = ob.block_tables(A, B, 'address', 'address', word_level=True, overlap_size=3, l_output_attrs=['name', 'birth_year', 'address'], r_output_attrs=['name', 'birth_year', 'address'] s...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
In the above, we used word-level tokenizer. Overlap blocker also supports q-gram based tokenizer and it can be used as follows:
# Set the word_level to be False and set the value of q (using q_val) C2 = ob.block_tables(A, B, 'address', 'address', word_level=False, q_val=3, overlap_size=3, l_output_attrs=['name', 'birth_year', 'address'], r_output_attrs=['name', 'birth_year', 'address'], ...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Updating Stopwords Commands in the Overlap Blocker removes some stop words by default. You can avoid this by specifying rem_stop_words parameter to False
# Set the parameter to remove stop words to False C3 = ob.block_tables(A, B, 'address', 'address', word_level=True, overlap_size=3, rem_stop_words=False, l_output_attrs=['name', 'birth_year', 'address'], r_output_attrs=['name', 'birth_year', 'address'], show_...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
You can check what stop words are getting removed like this:
ob.stop_words
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
You can update this stop word list (with some domain specific stop words) and do the blocking.
# Include Franciso as one of the stop words ob.stop_words.append('francisco') ob.stop_words # Set the word level tokenizer to be True C4 = ob.block_tables(A, B, 'address', 'address', word_level=True, overlap_size=3, l_output_attrs=['name', 'birth_year', 'address'], r_output_a...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Handling Missing Values If the input tuples have missing values in the blocking attribute, then they are ignored by default. You can set allow_missing_values to be True to include all possible tuple pairs with missing values.
# Introduce some missing value A1 = em.read_csv_metadata(path_A, key='ID') A1.ix[0, 'address'] = pd.np.NaN # Set the word level tokenizer to be True C5 = ob.block_tables(A1, B, 'address', 'address', word_level=True, overlap_size=3, allow_missing=True, l_output_attrs=['name', 'birth_year', 'address'...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Block a Candidata Set To Produce Reduced Set of Tuple Pairs
#Instantiate the overlap blocker ob = em.OverlapBlocker()
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
In the above, we see that the candidate set produced after blocking over input tables include tuple pairs that have at least three tokens in overlap. Adding to that, we will assume that two persons with no overlap of their names cannot refer to the same person. So, we block the candidate set of tuple pairs on name. Tha...
# Specify the tokenization to be 'word' level and set overlap_size to be 1. C6 = ob.block_candset(C1, 'name', 'name', word_level=True, overlap_size=1, show_progress=False) C6
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
In the above, we saw that word level tokenization was used to tokenize the names. You can also use q-gram tokenization like this:
# Specify the tokenization to be 'word' level and set overlap_size to be 1. C7 = ob.block_candset(C1, 'name', 'name', word_level=False, q_val= 3, overlap_size=1, show_progress=False) C7.head()
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Handling Missing Values As we saw with block_tables, you can include all the possible tuple pairs with the missing values using allow_missing parameter block the candidate set with the updated set of stop words.
# Introduce some missing values A1.ix[2, 'name'] = pd.np.NaN C8 = ob.block_candset(C5, 'name', 'name', word_level=True, overlap_size=1, allow_missing=True, show_progress=False)
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Block Two tuples To Check If a Tuple Pair Would Get Blocked We can apply overlap blocking to a tuple pair to check if it is going to get blocked. For example, we can check if the first tuple from A and B will get blocked if we block on address.
# Display the first tuple from table A A.ix[[0]] # Display the first tuple from table B B.ix[[0]] # Instantiate Attr. Equivalence Blocker ob = em.OverlapBlocker() # Apply blocking to a tuple pair from the input tables on zipcode and get blocking status status = ob.block_tuples(A.ix[0], B.ix[0],'address', 'address', ...
notebooks/guides/step_wise_em_guides/.ipynb_checkpoints/Performing Blocking Using Built-In Blockers (Overlap Blocker)-checkpoint.ipynb
anhaidgroup/py_entitymatching
bsd-3-clause
Use the numpy.arange method to generate 1000 days of data.
tdays = np.arange(0, 1E3) z = 2.0 # redshift tau = 300 # damping timescale
notebooks/time_series/sample_time_series.ipynb
cavestruz/MLPipeline
mit
Use the help function to figure out how to generate a dataset of this evenly spaced damped random walk over the 1000 days. Add errors to your 1000 points using numpy.random.normal. Note, you will need 1000 points, each centered on the actual data point, and assume a sigma 0.1. Randomly select a subsample of 200 data...
from sklearn.gaussian_process import GaussianProcess
notebooks/time_series/sample_time_series.ipynb
cavestruz/MLPipeline
mit
Define a covariance function as the one dimensional squared-exponential covariance function described in class. This will be a function of x1, x2, and the bandwidth h. Name this function covariance_squared_exponential. Generate values for the x-axis as 1000 evenly points between 0 and 10 using numpy.linspace. Define...
gp = GaussianProcess(corr='squared_exponential', theta0=0.5, random_state=0)
notebooks/time_series/sample_time_series.ipynb
cavestruz/MLPipeline
mit
Note Scaling the variables will make optimization functions work better, so here going to scale the variable into [0,1] range
scaler = MinMaxScaler(feature_range=(0, 1)) df['scaled_pm2.5'] = scaler.fit_transform(np.array(df['pm2.5']).reshape(-1, 1)) df.head() plt.figure(figsize=(5.5, 5.5)) g = sns.lineplot(data=df['scaled_pm2.5'], color='purple') g.set_title('Scaled pm2.5 between 2010 and 2014') g.set_xlabel('Index') g.set_ylabel('scaled_pm...
sequencial_analysis/after_2020_practice/ts_RNN_basics_tf2.4.ipynb
hanhanwu/Hanhan_Data_Science_Practice
mit
Note In 2D array above for X_train, X_val, it means (number of samples, number of time steps) However RNN input has to be 3D array, (number of samples, number of time steps, number of features per timestep) Only 1 feature which is scaled_pm2.5 So, the code below converts 2D array to 3D array
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) X_val = X_val.reshape((X_val.shape[0], X_val.shape[1], 1)) print('Shape of arrays after reshaping:', X_train.shape, X_val.shape) import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import SimpleRNN from t...
sequencial_analysis/after_2020_practice/ts_RNN_basics_tf2.4.ipynb
hanhanwu/Hanhan_Data_Science_Practice
mit
Introduction The Corpus Callosum (CC) is the largest white matter structure in the central nervous system that connects both brain hemispheres and allows the communication between them. The CC has great importance in research studies due to the correlation between shape and volume with some subject's characteristics, s...
#Loading labeled segmentations seg_label = genfromtxt('../dataset/Seg_Watershed/watershed_label.csv', delimiter=',').astype('uint8') list_mask = seg_label[seg_label[:,1] == 0, 0][:20] #Extracting correct segmentations for mean signature list_normal_mask = seg_label[seg_label[:,1] == 0, 0][20:30] #Extracting correct na...
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
Shape signature for comparison Signature is a shape descriptor that measures the rate of variation along the segmentation contour. As shown in figure, the curvature $k$ in the pivot point $p$, with coordinates ($x_p$,$y_p$), is calculated using the next equation. This curvature depict the angle between the segments $\o...
n_list = len(list_mask) smoothness = 700 #Smoothness degree = 1 #Spline degree fit_res = 0.35 resols = np.arange(0.01,0.5,0.01) #Signature resolutions resols = np.insert(resols,0,fit_res) #Insert resolution for signature fitting points = 100 #Points of Spline reconstruction refer_wat = np.empty((n_list,resols.shape[0]...
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
In order to get a representative correct signature, mean signature per-resolution was generated using 20 correct signatures. The mean was calculated in each point.
refer_wat_mean = np.mean(refer_wat,axis=0) #Finding mean signature per resolution print "Mean signature size: ", refer_wat_mean.shape plt.figure() #Plotting mean signature plt.plot(refer_wat_mean[res_ex,:]) plt.title("Mean signature for res: %f"%(resols[res_ex])) plt.show()
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
Signature configuration Because of the mean signature was extracted for all the resolutions, it is necessary to find resolution in that diference between RMSE for correct signature and RMSE for erroneous signature is maximum. So, 20 news segmentations were used to find this optimal resolution, being divided as 10 corre...
n_list = np.amax((len(list_normal_mask),len(list_error_mask))) refer_wat_n = np.empty((n_list,resols.shape[0],points)) #Initializing correct signature vector refer_wat_e = np.empty((n_list,resols.shape[0],points)) #Initializing error signature vector for mask in xrange(n_list): #Loading correct mask mask_pn = ...
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
The RMSE over the 10 correct segmentations was compared with RMSE over the 10 erroneous segmentations. As expected, RMSE for correct segmentations was greater than RMSE for erroneous segmentations along all the resolutions. In general, this is true, but optimal resolution guarantee the maximum difference between both o...
rmse_nacum = np.sqrt(np.sum((refer_wat_mean - refer_wat_n)**2,axis=2)/(refer_wat_mean.shape[1])) rmse_eacum = np.sqrt(np.sum((refer_wat_mean - refer_wat_e)**2,axis=2)/(refer_wat_mean.shape[1])) dif_dis = rmse_eacum - rmse_nacum #Difference between erroneous signatures and correct signatures in_max_res = np.argmax(np....
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
The greatest difference resulted at resolution 0.09. In this resolution, threshold for separate erroneous and correct segmentations is established as 30% of the distance between the mean RMSE of the correct masks and the mean RMSE of the erroneous masks. Method testing Finally, method test was performed in the 145 subj...
n_resols = [fit_res, opt_res] #Resolutions for fitting and comparison #### Teste dataset (Watershed) #Loading labels seg_label = genfromtxt('../dataset/Seg_Watershed/watershed_label.csv', delimiter=',').astype('uint8') all_seg = np.hstack((seg_label[seg_label[:,1] == 0, 0][30:], seg_label[seg_lab...
deliver/.ipynb_checkpoints/010617-WJGH-art_struc-checkpoint.ipynb
ecalio07/enron-paper
gpl-3.0
This will generate a very small file named HMB_4.bag.idx.bin in the same folder. Copy the bag file in HDFS Using your favorite tool put the bag file in your working HDFS folder. Note: keep the index json file as configuration to your jobs, do not put small files in HDFS. For convenience we already provide an example fi...
from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession sparkConf = SparkConf() sparkConf.setMaster("local[*]") sparkConf.setAppName("ros_hadoop") sparkConf.set("spark.jars", "../lib/protobuf-java-3.3.0.jar,../lib/rosbaginputformat.jar,../lib/scala-library-2.11.8.jar") spark = SparkSession.bu...
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Create an RDD from the Rosbag file Note: your HDFS address might differ.
fin = sc.newAPIHadoopFile( path = "hdfs://127.0.0.1:9000/user/root/HMB_4.bag", inputFormatClass = "de.valtech.foss.RosbagMapInputFormat", keyClass = "org.apache.hadoop.io.LongWritable", valueClass = "org.apache.hadoop.io.MapWritable", conf = {"RosbagInputFormat....
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Interpret the Messages To interpret the messages we need the connections. We could get the connections as configuration as well. At the moment we decided to collect the connections into Spark driver in a dictionary and use it in the subsequent RDD actions. Note in the next version of the RosbagInputFormater alternative...
conn_a = fin.filter(lambda r: r[1]['header']['op'] == 7).map(lambda r: r[1]).collect() conn_d = {str(k['header']['topic']):k for k in conn_a} # see topic names conn_d.keys()
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Load the python map functions from src/main/python/functions.py
%run -i ../src/main/python/functions.py
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Use of msg_map to apply a function on all messages Python rosbag.bag needs to be installed on all Spark workers. The msg_map function (from src/main/python/functions.py) takes three arguments: 1. r = the message or RDD record Tuple 2. func = a function (default str) to apply to the ROS message 3. conn = a connection to...
%matplotlib nbagg # use %matplotlib notebook in python3 from functools import partial import pandas as pd import numpy as np # Take messages from '/imu/data' topic using default str func rdd = fin.flatMap( partial(msg_map, conn=conn_d['/imu/data']) ) print(rdd.take(1)[0])
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Image data from camera messages An example of taking messages using a func other than default str. In our case we apply a lambda to messages from from '/center_camera/image_color/compressed' topic. As usual with Spark the operation will happen in parallel on all workers.
from PIL import Image from io import BytesIO res = fin.flatMap( partial(msg_map, func=lambda r: r.data, conn=conn_d['/center_camera/image_color/compressed']) ).take(50) Image.open(BytesIO(res[48]))
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Plot fuel level The topic /vehicle/fuel_level_report contains 2215 ROS messages. Let us plot the header.stamp in seconds vs. fuel_level using a pandas dataframe
def f(msg): return (msg.header.stamp.secs, msg.fuel_level) d = fin.flatMap( partial(msg_map, func=f, conn=conn_d['/vehicle/fuel_level_report']) ).toDF().toPandas() d.set_index('_1').plot()
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Machine Learning models on Spark workers A dot product Keras "model" for each message from a topic. We will compare it with the one computed with numpy. Note that the imports happen in the workers and not in driver. On the other hand the connection dictionary is sent over the closure.
def f(msg): from keras.layers import dot, Dot, Input from keras.models import Model linear_acceleration = { 'x': msg.linear_acceleration.x, 'y': msg.linear_acceleration.y, 'z': msg.linear_acceleration.z, } linear_acceleration_covariance = np.array(msg.linear_acceler...
doc/Tutorial.ipynb
vasco-da-gama/ros_hadoop
apache-2.0
Please re-run the above cell if you are getting any incompatible warnings and errors.
import pprint import tensorflow_datasets as tfds ratings = tfds.load("movielens/100k-ratings", split="train") for x in ratings.take(1).as_numpy_iterator(): pprint.pprint(x)
courses/machine_learning/deepdive2/recommendation_systems/labs/featurization.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
There are a couple of key features here: Movie title is useful as a movie identifier. User id is useful as a user identifier. Timestamps will allow us to model the effect of time. The first two are categorical features; timestamps are a continuous feature. Turning categorical features into embeddings A categorical fe...
import numpy as np import tensorflow as tf movie_title_lookup = tf.keras.layers.experimental.preprocessing.StringLookup()
courses/machine_learning/deepdive2/recommendation_systems/labs/featurization.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
The layer itself does not have a vocabulary yet, but we can build it using our data.
movie_title_lookup.adapt(ratings.map(lambda x: x["movie_title"])) print(f"Vocabulary: {movie_title_lookup.get_vocabulary()[:3]}")
courses/machine_learning/deepdive2/recommendation_systems/labs/featurization.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Once we have this we can use the layer to translate raw tokens to embedding ids:
movie_title_lookup(["Star Wars (1977)", "One Flew Over the Cuckoo's Nest (1975)"])
courses/machine_learning/deepdive2/recommendation_systems/labs/featurization.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Note that the layer's vocabulary includes one (or more!) unknown (or "out of vocabulary", OOV) tokens. This is really handy: it means that the layer can handle categorical values that are not in the vocabulary. In practical terms, this means that the model can continue to learn about and make recommendations even using...
# We set up a large number of bins to reduce the chance of hash collisions. num_hashing_bins = 200_000 movie_title_hashing = tf.keras.layers.experimental.preprocessing.Hashing( num_bins=num_hashing_bins )
courses/machine_learning/deepdive2/recommendation_systems/labs/featurization.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0