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.get_label_names(y_pred), util.get_label_names(dfn_pred)) util.plotconfusion(util.get_label_names(y_pred), util.get_label_names(cnn_pred))
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 tell you the general format the autograder is expecting return df.iloc[0] # You can examine what your function returns by calling it in the cell. If you have questions # about the assignment formats, check out the discussion forums for any FAQs answer_zero()
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 a single string value.
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 should return a Series named Points of length 146
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 the variable names. The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate. Question 5 Which state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for future questions too...) This function should return a single string value.
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() answer_six()
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 largest change in the period would be |130-80| = 50. This function should return a single string value.
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 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).
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_keep] return ansdf answer_eight()
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 class as an image.
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(labels_original)) for i, uclass in enumerate(uclasses): print(uclass,counts[i]) first_example = np.where(labels_original==uclass)[0][0] plt.imshow(images[first_example]) plt.title(galaxy10cls_lookup(uclass)) plt.show()
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 images for our MLP images_top_two_flat = images_top_two.reshape(len(images_top_two),-1) #Normalize the flux of the images here images_top_two_flat = (images_top_two_flat - torch.mean(images_top_two_flat))/torch.std(images_top_two_flat)
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.Linear(self.input_size, self.hidden_size) self.outputlayer = torch.nn.Linear(self.hidden_size, 2) self.sigmoid = torch.nn.Sigmoid() self.softmax = torch.nn.Softmax() def forward(self, x): layer1 = self.hiddenlayer(x) activation = self.sigmoid(layer1) layer2 = self.outputlayer(activation) activation2 = self.sigmoid(layer1) layer3 = self.outputlayer(activation2) output = self.softmax(layer3) return output
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() # compute the model output myoutput = model(training_data) # calculate loss loss = criterion(myoutput, training_labels) # credit assignment loss.backward() # update model weights optimizer.step() # STUDENTS ADD THIS PART output_test = model(test_data) loss_test = criterion(output_test, test_labels) plt.plot(epoch,loss.detach().numpy(),'ko') plt.plot(epoch,loss_test.detach().numpy(),'ro') print(epoch,loss.detach().numpy()) plt.show()
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' % acc)
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.g., if the galaxy class breakdowns are 1:2:3, the weights would be 6:3:2).
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 = torch.nn.Linear(self.input_size, self.hidden_size) self.outputlayer = torch.nn.Linear(self.hidden_size, 3) self.sigmoid = torch.nn.Sigmoid() self.softmax = torch.nn.Softmax() def forward(self, x): layer1 = self.hiddenlayer(x) activation = self.sigmoid(layer1) layer2 = self.outputlayer(activation) activation2 = self.sigmoid(layer1) layer3 = self.outputlayer(activation2) output = self.softmax(layer3) return output #Only work with 0,1,2 gind = np.where((labels_original==0) | (labels_original==1) | (labels_original==2)) images_top_three = images[gind] labels_top_three = labels_original[gind] x,counts = np.unique(labels_top_three,return_counts=True) print(counts) torch.set_default_dtype(torch.float) labels_top_three_one_hot = F.one_hot(torch.tensor(labels_top_three - np.min(labels_top_three)).long(), num_classes=3) images_top_three = torch.tensor(images_top_three).float() labels_top_three_one_hot = labels_top_three_one_hot.float() # we're going to flatten the images for our MLP images_top_three_flat = images_top_three.reshape(len(images_top_three),-1) #Normalize the flux of the images here images_top_three_flat = (images_top_three_flat - torch.mean(images_top_three_flat))/torch.std(images_top_three_flat) images_train, images_test, labels_train, labels_test = train_test_split( images_top_three_flat, labels_top_three_one_hot, test_size=0.33, random_state=42) # train the model def train_model(training_data,training_labels, test_data,test_labels, model): # define the optimization criterion = torch.nn.CrossEntropyLoss(weight=torch.Tensor(np.sum(counts)/counts)) optimizer = torch.optim.SGD(model.parameters(), lr=0.005,momentum=0.9) for epoch in range(100): # clear the gradient optimizer.zero_grad() # compute the model output myoutput = model(training_data) # calculate loss loss = criterion(myoutput, training_labels) # credit assignment loss.backward() # update model weights optimizer.step() # STUDENTS ADD THIS PART output_test = model(test_data) loss_test = criterion(output_test, test_labels) plt.plot(epoch,loss.detach().numpy(),'ko') plt.plot(epoch,loss_test.detach().numpy(),'ro') print(epoch,loss.detach().numpy()) plt.show() model = MLP_new(np.shape(images_train[0])[0],50) train_model(images_train, labels_train, images_test, labels_test, model) # 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' % acc) 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
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('Success: test_compress') def main(): test = TestCompress() test.test_compress(compress_string) if __name__ == '__main__': main()
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="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/probability/examples/Understanding_TensorFlow_Distributions_Shapes.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a></td> </table>
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 オブジェクトのプロパティですが、サンプルの形状は sample または log_prob への特定の呼び出しに関連付けられています。 このノートブックでは、例を使ってこれらの概念を説明していくので、すぐに分からなくても、心配する必要はありません。 また、これらの概念の概要については、このブログ記事を参照してください。 TensorFlow Eager に関する注意 このノートブックは、すべて TensorFlow Eager を使用して記述されています。提示された概念は Eager に依存していませんが、Eager では、Distribution オブジェクトが Python で作成されるときに、分布バッチとイベントの形状が評価されます(したがって既知です)。一方、グラフ(非 Eager モード)では、グラフが実行されるまでイベントとバッチの形状が決定されていない分布を定義することができます。 スカラー分布 上記のように、Distribution オブジェクトではイベントとバッチの形状が定義されています。まず、分布を説明するユーティリティから始めます。
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.Poisson(rate=[[1.]], name='One Poisson Expanded Batch') ] describe_distributions(poisson_distributions)
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') ] describe_distributions(normal_distributions)
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 = [] であるため、サンプルから返されるテンソルの形状は [sample_shape, batch_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: print(distribution) for sample_shape in sample_shapes: describe_sample_tensor_shape(sample_shape, distribution) print() sample_shapes = [1, 2, [1, 5], [3, 4, 5]] describe_sample_tensor_shapes(poisson_distributions, sample_shapes) describe_sample_tensor_shapes(normal_distributions, sample_shapes)
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 は 分布のバッチおよびイベントの形状に一致します。スカラー分布の場合は、event_shape = [] なので、入力テンソルの形状は [sample_shape, batch_shape] です。この場合、[sample_shape, batch_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 を log_prob 計算している分布の [batch_shape, event_shape] に対してブロードキャストします。詳しく説明すると、t' がすでに分布と一致している次元の場合は何もせず、t' の次元がシングルトンの場合は、そのシングルトンを適切な数で複製します。その他の場合はエラーです。(スカラー分布の場合、event_shape = [] であるため、 batch_shape に対してのみブロードキャストします。) これで、log_prob を計算できるようになりました。結果のテンソルの形状は、[sample_shape, batch_shape] です。sample_shape は、右端の次元 n の左側にある t または t' の任意の次元として定義されます(sample_shape = shape(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 the same thing. No broadcasting. poisson_2_by_3.log_prob([[1., 10., 100.]]) # Input is [1, 3] broadcast to [2, 3]. poisson_2_by_3.log_prob([[1., 10., 100.], [1., 10., 100.]]) # Equivalent to above. No broadcasting. poisson_2_by_3.log_prob([[1., 1., 1.], [2., 2., 2.]]) # No broadcasting. poisson_2_by_3.log_prob([[1.], [2.]]) # Equivalent to above. Input shape [2, 1] broadcast to [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., 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.Multinomial(total_count=[100., 1000.], probs=[.5, .4, .1], name='Two Multinomials Same Probs'), tfd.Multinomial(total_count=100., probs=[[.5, .4, .1], [.1, .2, .7]], name='Two Multinomials Same Counts'), tfd.Multinomial(total_count=[100., 1000.], probs=[[.5, .4, .1], [.1, .2, .7]], name='Two Multinomials Different Everything') ] describe_distributions(multinomial_distributions)
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 = validation_curve(model, X, y, param_name="max_depth", param_range=param_range, cv=5) training_scores.shape def plot_validation_curve(parameter_values, train_scores, validation_scores): train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) validation_scores_mean = np.mean(validation_scores, axis=1) validation_scores_std = np.std(validation_scores, axis=1) plt.fill_between(parameter_values, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(parameter_values, validation_scores_mean - validation_scores_std, validation_scores_mean + validation_scores_std, alpha=0.1, color="g") plt.plot(parameter_values, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(parameter_values, validation_scores_mean, 'o-', color="g", label="Cross-validation score") plt.ylim(validation_scores_mean.min() - .1, train_scores_mean.max() + .1) plt.legend(loc="best") plt.figure() plot_validation_curve(param_range, training_scores, validation_scores)
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 the answers from the workers annotation_separator: string that separates between the crowd annotations in outputColumns open_ended_task: boolean variable defining whether the task is open-ended (i.e. the possible crowd annotations are not known beforehand, like in the case of free text input); in the task that we are processing, workers pick the answers from a pre-defined list, therefore the task is not open ended, and this variable is set to False annotation_vector: list of possible crowd answers, mandatory to declare when open_ended_task is False; for our task, this is the list of relations processJudgments: method that defines processing of the raw crowd data; for this task, we process the crowd answers to correspond to the values in annotation_vector Same examples of possible processing functions of crowd answers are given below:
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_list = keywords.split(separator) corrected_keywords = [] for keyword in keywords_list: words_in_keyword = keyword.split(" ") corrected_keyword = [] for word in words_in_keyword: correct_word = spell(word) corrected_keyword.append(correct_word) corrected_keywords.append(" ".join(corrected_keyword)) return separator.join(corrected_keywords) def cleanup_keywords(keywords, separator): keywords_list = keywords.split(separator) stopset = set(stopwords.words('english')) filtered_keywords = [] for keyword in keywords_list: tokens = nltk.word_tokenize(keyword) cleanup = " ".join(filter(lambda word: str(word) not in stopset or str(word) == "no" or str(word) == "not", keyword.split())) filtered_keywords.append(cleanup) return separator.join(filtered_keywords) def nltk2wn_tag(nltk_tag): if nltk_tag.startswith('J'): return wordnet.ADJ elif nltk_tag.startswith('V'): return wordnet.VERB elif nltk_tag.startswith('N'): return wordnet.NOUN elif nltk_tag.startswith('R'): return wordnet.ADV else: return None def lemmatize_keywords(keywords, separator): keywords_list = keywords.split(separator) lematized_keywords = [] for keyword in keywords_list: nltk_tagged = nltk.pos_tag(nltk.word_tokenize(str(keyword))) wn_tagged = map(lambda x: (str(x[0]), nltk2wn_tag(x[1])), nltk_tagged) res_words = [] for word, tag in wn_tagged: if tag is None: res_word = wordnet._morphy(str(word), wordnet.NOUN) if res_word == []: res_words.append(str(word)) else: if len(res_word) == 1: res_words.append(str(res_word[0])) else: res_words.append(str(res_word[1])) else: res_word = wordnet._morphy(str(word), tag) if res_word == []: res_words.append(str(word)) else: if len(res_word) == 1: res_words.append(str(res_word[0])) else: res_words.append(str(res_word[1])) lematized_keyword = " ".join(res_words) lematized_keywords.append(lematized_keyword) return separator.join(lematized_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 match the values in annotation_vector for col in self.outputColumns: # transform to lowercase judgments[col] = judgments[col].apply(lambda x: str(x).lower()) # remove square brackets from annotations judgments[col] = judgments[col].apply(lambda x: str(x).replace('[]','no tags')) judgments[col] = judgments[col].apply(lambda x: str(x).replace('[','')) judgments[col] = judgments[col].apply(lambda x: str(x).replace(']','')) # remove the quotes around the annotations judgments[col] = judgments[col].apply(lambda x: str(x).replace('"','')) # apply custom processing functions judgments[col] = judgments[col].apply(lambda x: correct_words(str(x), self.annotation_separator)) judgments[col] = judgments[col].apply(lambda x: "no tag" if cleanup_keywords(str(x), self.annotation_separator) == '' else cleanup_keywords(str(x), self.annotation_separator)) judgments[col] = judgments[col].apply(lambda x: lemmatize_keywords(str(x), self.annotation_separator)) return judgments
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, key='ID') B = em.read_csv_metadata(path_B, key='ID') A.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
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 Produce a Candidate Set of Tuple Pairs
# 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. That is, we block all the tuple pairs that do not share at least 3 tokens in address.
# 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'] show_progress=False) # Display first 5 tuple pairs in the candidate set. C1.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
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'], show_progress=False) # Display first 5 tuple pairs C2.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
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_progress=False) # Display first 5 tuple pairs C3.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
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_attrs=['name', 'birth_year', 'address'], show_progress=False) C4.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 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'], r_output_attrs=['name', 'birth_year', 'address'], show_progress=False) len(C5) C5
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. That is, we block all the tuple pairs that have no overlap of tokens.
# 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', overlap_size=1, show_progress=False) # Print the blocking status print(status)
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 points from your generated dataset. This is now unevenly spaced, and will serve as your observed lightcurve. Plot the observed lightcurve. Use the help menu to figure out how to calculate the autocorrelation function of your lightcurve with ACF_scargle. In this next example, we will explore data drawn from a gaussian process.
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 a bandwidth of h=1. Generate an output of your covariance_squared_exponential with x as x1, x[:,None] as x2, and h as the bandwidth. Use numpy.random.multivariate_normal to generate a numpy array of the same length as your x-axis points. Each point is centered on 0 (your mean is a 1-d array of zeros), and your covariance is the output of your covariance_squared_exponential above. Choose two values in your x-range as sample x values, and put in an array, x_sample_test. Choose a function (e.g. numpy.cos) as your example function to constrain. Define an instance of a gaussian proccess
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_pm2.5 readings') # 2014 data as validation data, before 2014 as training data split_date = datetime.datetime(year=2014, month=1, day=1, hour=0) df_train = df.loc[df['datetime']<split_date] df_val = df.loc[df['datetime']>=split_date] print('Shape of train:', df_train.shape) print('Shape of test:', df_val.shape) df_val.reset_index(drop=True, inplace=True) df_val.head() # The way this works is to have the first nb_timesteps-1 observations as X and nb_timesteps_th as the target, ## collecting the data with 1 stride rolling window. def makeXy(ts, nb_timesteps): """ Input: ts: original time series nb_timesteps: number of time steps in the regressors Output: X: 2-D array of regressors y: 1-D array of target """ X = [] y = [] for i in range(nb_timesteps, ts.shape[0]): X.append(list(ts.loc[i-nb_timesteps:i-1])) y.append(ts.loc[i]) X, y = np.array(X), np.array(y) return X, y X_train, y_train = makeXy(df_train['scaled_pm2.5'], 7) print('Shape of train arrays:', X_train.shape, y_train.shape) print(X_train[0], y_train[0]) print(X_train[1], y_train[1]) X_val, y_val = makeXy(df_val['scaled_pm2.5'], 7) print('Shape of validation arrays:', X_val.shape, y_val.shape) print(X_val[0], y_val[0]) print(X_val[1], y_val[1])
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 tensorflow.keras.layers import Dense, Dropout, Input from tensorflow.keras.models import load_model from tensorflow.keras.callbacks import ModelCheckpoint from sklearn.metrics import mean_absolute_error tf.random.set_seed(10) model = Sequential() model.add(SimpleRNN(32, input_shape=(X_train.shape[1:]))) model.add(Dropout(0.2)) model.add(Dense(1, activation='linear')) model.compile(optimizer='rmsprop', loss='mean_absolute_error', metrics=['mae']) model.summary() save_weights_at = 'basic_rnn_model' save_best = ModelCheckpoint(save_weights_at, monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=False, mode='min', save_freq='epoch') history = model.fit(x=X_train, y=y_train, batch_size=16, epochs=20, verbose=1, callbacks=[save_best], validation_data=(X_val, y_val), shuffle=True) # load the best model best_model = load_model('basic_rnn_model') # Compare the prediction with y_true preds = best_model.predict(X_val) pred_pm25 = scaler.inverse_transform(preds) pred_pm25 = np.squeeze(pred_pm25) # Measure MAE of y_pred and y_true mae = mean_absolute_error(df_val['pm2.5'].loc[7:], pred_pm25) print('MAE for the validation set:', round(mae, 4)) mae = mean_absolute_error(df_val['scaled_pm2.5'].loc[7:], preds) print('MAE for the scaled validation set:', round(mae, 4)) # Check the metrics and loss of each apoch mae = history.history['mae'] val_mae = history.history['val_mae'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(mae)) plt.plot(epochs, mae, 'bo', label='Training MAE') plt.plot(epochs, val_mae, 'b', label='Validation MAE') plt.title('Training and Validation MAE') plt.legend() plt.figure() # Here I was using MAE as loss too, that's why they lookedalmost the same... plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and Validation loss') plt.legend() plt.show()
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, such as: gender, age, numeric and mathematical skills and handedness. In addition, some neurodegenerative diseases like Alzheimer, autism, schizophrenia and dyslexia could cause CC shape deformation. CC segmentation is a necessary step for morphological and physiological features extraction in order to analyze the structure in image-based clinical and research applications. Magnetic Resonance Imaging (MRI) is the most suitable image technique for CC segmentation due to its ability to provide contrast between brain tissues however CC segmentation is challenging because of the shape and intensity variability between subjects, volume partial effect in diffusion MRI, fornex proximity and narrow areas in CC. Among the known MRI modalities, Diffusion-MRI arouses special interest to study the CC, despite its low resolution and high complexity, since it provides useful information related to the organization of brain tissues and the magnetic field does not interfere with the diffusion process itself. Some CC segmentation approaches using Diffusion-MRI were found in the literature. Niogi et al. proposed a method based on thresholding, Freitas et al. e Rittner et al. proposed region methods based on Watershed transform, Nazem-Zadeh et al. implemented based on level surfaces, Kong et al. presented an clustering algorithm for segmentation, Herrera et al. segmented CC directly in diffusion weighted imaging (DWI) using a model based on pixel classification and Garcia et al. proposed a hybrid segmentation method based on active geodesic regions and level surfaces. With the growing of data and the proliferation of automatic algorithms, segmentation over large databases is affordable. Therefore, error automatic detection is important in order to facilitate and speed up filter on CC segmentation databases. presented proposals for content-based image retrieval (CBIR) using shape signature of the planar object representation. In this work, a method for automatic detection of segmentation error in large datasets is proposed based on CC shape signature. Signature offers shape characterization of the CC and therefore it is expected that a "typical correct signature" represents well any correct segmentation. Signature is extracted measuring curvature along segmentation contour. The method was implemented in three main stages: mean correct signature generation, signature configuration and method testing. The first one takes 20 corrects segmentations and generates one correct signature of reference (typical correct signature), per-resolution, using mean values in each point. The second stage stage takes 10 correct segmentations and 10 erroneous segmentations and adjusts the optimal resolution and threshold, based on mean correct signature, that lets detection of erroneous segmentations. The third stage labels a new segmentation as correct and erroneous comparing with the mean signature using optimal resolution and threshold. <img src="../figures/workflow.png"> The comparison between signatures is done using root mean square error (RMSE). True label for each segmentation was done visually. Correct segmentation corresponds to segmentations with at least 50% of agreement with the structure. It is expected that RMSE for correct segmentations is lower than RMSE associated to erroneous segmentation when compared with a typical correct segmentation.
#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 names for configuration list_error_mask = seg_label[seg_label[:,1] == 1, 0][:10] #Extracting correct names for configuration mask_correct = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(list_mask[0])) mask_error = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(list_error_mask[0])) plt.figure() plt.axis('off') plt.imshow(mask_correct,'gray',interpolation='none') plt.title("Correct segmentation example") plt.show() plt.figure() plt.axis('off') plt.imshow(mask_error,'gray',interpolation='none') plt.title("Erroneous segmentation example") plt.show()
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 $\overline{(x_{p-ls},y_{p-ls})(x_p,y_p)}$ and $\overline{(x_p,y_p)(x_{p+ls},y_{p+ls})}$. These segments are located to a distance $ls>0$, starting in a pivot point and finishing in anterior and posterior points, respectively. The signature is obtained calculating the curvature along all segmentation contour. \begin{equation} \label{eq:per1} k(x_p,y_p) = \arctan\left(\frac{y_{p+ls}-y_p}{x_{p+ls}-x_p}\right)-\arctan\left(\frac{y_p-y_{p-ls}}{x_p-x_{p-ls}}\right) \end{equation} <img src="../figures/curvature.png"> Signature construction is performed from segmentation contour of the CC. From contour, spline is obtained. Spline purpose is twofold: to get a smooth representation of the contour and to facilitate calculation of the curvature using its parametric representation. The signature is obtained measuring curvature along spline. $ls$ is the parametric distance between pivot point and both posterior and anterior points and it determines signature resolution. By simplicity, $ls$ is measured in percentage of reconstructed spline points. In order to achieve quantitative comparison between two signatures root mean square error (RMSE) is introduced. RMSE measures distance, point to point, between signatures $a$ and $b$ along all points $p$ of signatures. \begin{equation} \label{eq:per4} RMSE = \sqrt{\frac{1}{P}\sum_{p=1}^{P}(k_{ap}-k_{bp})^2} \end{equation} Frequently, signatures of different segmentations are not fitted along the 'x' axis because of the initial point on the spline calculation starts in different relative positions. This makes impossible to compare directly two signatures and therefore, a prior fitting process must be accomplished. The fitting process is done shifting one of the signature while the other is kept fixed. For each shift, RMSE between the two signatures is measured. The point giving the minor error is the fitting point. Fitting was done at resolution $ls = 0.35$. This resolution represents globally the CC's shape and eases their fitting. After fitting, RMSE between signatures can be measured in order to achieve final quantitative comparison. Signature for segmentation error detection For segmentation error detection, a typical correct signature is obtained calculating mean over a group of signatures from correct segmentations. Because of this signature could be used in any resolution, $ls$ must be chosen for achieve segmentation error detection. The optimal resolution must be able to return the greatest RMSE difference between correct and erroneous segmentation when compared with a typical correct signature. In the optimal resolution, a threshold must be chosen for separate erroneous and correct segmentations. This threshold stays between RMSE associated to correct ($RMSE_E$) and erroneous ($RMSE_C$) signatures and it is given by the next equation where N (in percentage) represents proximity to correct or erroneous RMSE. If RMSE calculated over a group of signatures, mean value is applied. \begin{equation} \label{eq:eq3} th = N*(\overline{RMSE_E}-\overline{RMSE_C})+\overline{RMSE_C} \end{equation} Experiments and results In this work, comparison of signatures through RMSE is used for segmentation error detection in large datasets. For this, it will be calculated a mean correct signature based on 20 correct segmentation signatures. This mean correct signature represents a tipycal correct segmentation. For a new segmentation, signature is extracted and compared with mean signature. For experiments, DWI from 152 subjects at the University of Campinas, were acquired on a Philips scanner Achieva 3T in the axial plane with a $1$x$1mm$ spatial resolution and $2mm$ slice thickness, along $32$ directions ($b-value=1000s/mm^2$, $TR=8.5s$, and $TE=61ms$). All data used in this experiment was acquired through a project approved by the research ethics committee from the School of Medicine at UNICAMP. From each acquired DWI volume, only the midsaggital slice was used. Three segmentation methods were implemented to obtained binary masks over a 152 subject dataset: Watershed, ROQS and pixel-based. 40 Watershed segmentations were chosen as follows: 20 correct segmentations for mean correct signature generation and 10 correct and 10 erroneous segmentations for signature configuration stage. Watershed was chosen to generate and adjust the mean signature because of its higher error rate and its variability in the erroneous segmentation shape. These characteristics allow improve generalization. The method was tested on the remaining Watershed segmentations (108 masks) and two additional segmentations methods: ROQS (152 masks) and pixel-based (152 masks). Mean correct signature generation In this work, segmentations based on Watershed method were used for implementation of the first and second stages. From the Watershed dataset, 20 correct segmentations were chosen. Spline for each one was obtained from segmentation contour. The contour was obtained using mathematical morphology, applying xor logical operation, pixel-wise, between original segmentation and the eroded version of itself by an structuring element b: \begin{equation} \label{eq:per2} G_E = XOR(S,S \ominus b) \end{equation} From contour, it is calculated spline. The implementation, is a B-spline (Boor's basic spline). This formulation has two parameters: degree, representing polynomial degrees of the spline, and smoothness, being the trade off between proximity and smoothness in the fitness of the spline. Degree was fixed in 5 allowing adequate representation of the contour. Smoothness was fixed in 700. This value is based on the mean quantity of pixels of the contour that are passed for spline calculation. The curvature was measured over 500 points over the spline to generate the signature along 20 segmentations. Signatures were fitted to make possible comparison (Fig. signatures). Fitting resolution was fixed in 0.35.
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],points)) #Initializing signature vector for mask in xrange(n_list): mask_p = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(list_mask[mask])) refer_temp = sign_extract(mask_p, resols) #Function for shape signature extraction refer_wat[mask] = refer_temp if mask > 0: #Fitting curves using the first one as basis prof_ref = refer_wat[0] refer_wat[mask] = sign_fit(prof_ref[0], refer_temp) #Function for signature fitting print "Signatures' vector size: ", refer_wat.shape res_ex = 10 plt.figure() plt.plot(refer_wat[:,res_ex,:].T) plt.title("Signatures for res: %f"%(resols[res_ex])) plt.show()
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 correct segmentations and 10 erroneous segmentations. For each segmentation, it was extracted signature for all resolutions.
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 = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(list_normal_mask[mask])) refer_temp_n = sign_extract(mask_pn, resols) #Function for shape signature extraction refer_wat_n[mask] = sign_fit(refer_wat_mean[0], refer_temp_n) #Function for signature fitting #Loading erroneous mask mask_pe = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(list_error_mask[mask])) refer_temp_e = sign_extract(mask_pe, resols) #Function for shape signature extraction refer_wat_e[mask] = sign_fit(refer_wat_mean[0], refer_temp_e) #Function for signature fitting print "Correct segmentations' vector: ", refer_wat_n.shape print "Erroneous segmentations' vector: ", refer_wat_e.shape plt.figure() plt.plot(refer_wat_n[:,res_ex,:].T) plt.title("Correct signatures for res: %f"%(resols[res_ex])) plt.show() plt.figure() plt.plot(refer_wat_e[:,res_ex,:].T) plt.title("Erroneous signatures for res: %f"%(resols[res_ex])) plt.show()
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 of RMSE results: correct and erroneous. So, to find optimal resolution, difference between correct and erroneous RMSE was calculated over all resolutions.
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.mean(dif_dis,axis=0)) #Finding optimal resolution at maximum difference opt_res = resols[in_max_res] print "Optimal resolution for error detection: ", opt_res perc_th = 0.3 #Established percentage to threshold correct_max = np.mean(rmse_nacum[:,in_max_res]) #Finding threshold for separate segmentations error_min = np.mean(rmse_eacum[:,in_max_res]) th_res = perc_th*(error_min-correct_max)+correct_max print "Threshold for separate segmentations: ", th_res #### Plotting erroneous and correct segmentation signatures ticksx_resols = ["%.2f" % el for el in np.arange(0.01,0.5,0.01)] #Labels for plot xticks ticksx_resols = ticksx_resols[::6] ticksx_index = np.arange(1,50,6) figpr = plt.figure() #Plotting mean RMSE for correct segmentations plt.boxplot(rmse_nacum[:,1:], showmeans=True) #Element 0 was introduced only for fitting, #in comparation is not used. plt.axhline(y=0, color='g', linestyle='--') plt.axhline(y=th_res, color='r', linestyle='--') plt.axvline(x=in_max_res, color='r', linestyle='--') plt.xlabel('Resolutions', fontsize = 12, labelpad=-2) plt.ylabel('RMSE correct signatures', fontsize = 12) plt.xticks(ticksx_index, ticksx_resols) plt.show() figpr = plt.figure() #Plotting mean RMSE for erroneous segmentations plt.boxplot(rmse_eacum[:,1:], showmeans=True) plt.axhline(y=0, color='g', linestyle='--') plt.axhline(y=th_res, color='r', linestyle='--') plt.axvline(x=in_max_res, color='r', linestyle='--') plt.xlabel('Resolutions', fontsize = 12, labelpad=-2) plt.ylabel('RMSE error signatures', fontsize = 12) plt.xticks(ticksx_index, ticksx_resols) plt.show() figpr = plt.figure() #Plotting difference for mean RMSE over all resolutions plt.boxplot(dif_dis[:,1:], showmeans=True) plt.axhline(y=0, color='g', linestyle='--') plt.axvline(x=in_max_res, color='r', linestyle='--') plt.xlabel('Resolutions', fontsize = 12, labelpad=-2) plt.ylabel('Difference RMSE signatures', fontsize = 12) plt.xticks(ticksx_index, ticksx_resols) plt.show()
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 subject dataset: Watershed dataset with 107 segmentations, ROQS dataset with 152 segmentations and pixel-based dataset with 152 segmentations. You can uncomment indicated blocks below to detailed results (mask and dataset-wise).
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_label[:,1] == 1, 0][10:])) #Extracting erroneous and correct names lab_seg = np.hstack((seg_label[seg_label[:,1] == 0, 1][30:], seg_label[seg_label[:,1] == 1, 1][10:])) #Extracting erroneous and correct labels refer_wat_mean_opt = np.vstack((refer_wat_mean[0],refer_wat_mean[in_max_res])) #Mean signature with fitting #and optimal resolution refer_seg = np.empty((all_seg.shape[0],len(n_resols),points)) #Initializing correct signature vector in_mask = 0 for mask in all_seg: mask_ = np.load('../dataset/Seg_Watershed/mask_wate_{}.npy'.format(mask)) refer_temp = sign_extract(mask_, n_resols) #Function for shape signature extraction refer_seg[in_mask] = sign_fit(refer_wat_mean_opt[0], refer_temp) #Function for signature fitting ###### Uncomment this block to see each segmentation with true and predicted labels #RMSE_ = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[in_mask,1])**2)/(refer_wat_mean_opt.shape[1])) #plt.figure() #plt.axis('off') #plt.imshow(mask_,'gray',interpolation='none') #plt.title("True label: {}, Predic. label: {}".format(lab_seg[in_mask],(RMSE_>th_res).astype('uint8'))) #plt.show() in_mask += 1 #### Segmentation evaluation result over all segmentations RMSE = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[:,1])**2,axis=1)/(refer_wat_mean_opt.shape[1])) pred_seg = RMSE > th_res #Apply threshold comp_seg = np.logical_not(np.logical_xor(pred_seg,lab_seg)) #Comparation method result with true labels acc_w = np.sum(comp_seg)/(1.0*len(comp_seg)) print "Final accuracy on Watershed {} segmentations: {}".format(len(comp_seg),acc_w) #### Teste dataset (ROQS) seg_label = genfromtxt('../dataset/Seg_ROQS/roqs_label.csv', delimiter=',').astype('uint8') #Loading labels all_seg = np.hstack((seg_label[seg_label[:,1] == 0, 0], seg_label[seg_label[:,1] == 1, 0])) #Extracting erroneous and correct names lab_seg = np.hstack((seg_label[seg_label[:,1] == 0, 1], seg_label[seg_label[:,1] == 1, 1])) #Extracting erroneous and correct labels refer_wat_mean_opt = np.vstack((refer_wat_mean[0],refer_wat_mean[in_max_res])) #Mean signature with fitting #and optimal resolution refer_seg = np.empty((all_seg.shape[0],len(n_resols),points)) #Initializing correct signature vector in_mask = 0 for mask in all_seg: mask_ = np.load('../dataset/Seg_ROQS/mask_roqs_{}.npy'.format(mask)) refer_temp = sign_extract(mask_, n_resols) #Function for shape signature extraction refer_seg[in_mask] = sign_fit(refer_wat_mean_opt[0], refer_temp) #Function for signature fitting ###### Uncomment this block to see each segmentation with true and predicted labels #RMSE_ = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[in_mask,1])**2)/(refer_wat_mean_opt.shape[1])) #plt.figure() #plt.axis('off') #plt.imshow(mask_,'gray',interpolation='none') #plt.title("True label: {}, Predic. label: {}".format(lab_seg[in_mask],(RMSE_>th_res).astype('uint8'))) #plt.show() in_mask += 1 #### Segmentation evaluation result over all segmentations RMSE = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[:,1])**2,axis=1)/(refer_wat_mean_opt.shape[1])) pred_seg = RMSE > th_res #Apply threshold comp_seg = np.logical_not(np.logical_xor(pred_seg,lab_seg)) #Comparation method result with true labels acc_r = np.sum(comp_seg)/(1.0*len(comp_seg)) print "Final accuracy on ROQS {} segmentations: {}".format(len(comp_seg),acc_r) #### Teste dataset (Pixel-based) seg_label = genfromtxt('../dataset/Seg_pixel/pixel_label.csv', delimiter=',').astype('uint8') #Loading labels all_seg = np.hstack((seg_label[seg_label[:,1] == 0, 0], seg_label[seg_label[:,1] == 1, 0])) #Extracting erroneous and correct names lab_seg = np.hstack((seg_label[seg_label[:,1] == 0, 1], seg_label[seg_label[:,1] == 1, 1])) #Extracting erroneous and correct labels refer_wat_mean_opt = np.vstack((refer_wat_mean[0],refer_wat_mean[in_max_res])) #Mean signature with fitting #and optimal resolution refer_seg = np.empty((all_seg.shape[0],len(n_resols),points)) #Initializing correct signature vector in_mask = 0 for mask in all_seg: mask_ = np.load('../dataset/Seg_pixel/mask_pixe_{}.npy'.format(mask)) refer_temp = sign_extract(mask_, n_resols) #Function for shape signature extraction refer_seg[in_mask] = sign_fit(refer_wat_mean_opt[0], refer_temp) #Function for signature fitting ###### Uncomment this block to see each segmentation with true and predicted labels #RMSE_ = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[in_mask,1])**2)/(refer_wat_mean_opt.shape[1])) #plt.figure() #plt.axis('off') #plt.imshow(mask_,'gray',interpolation='none') #plt.title("True label: {}, Predic. label: {}".format(lab_seg[in_mask],(RMSE_>th_res).astype('uint8'))) #plt.show() in_mask += 1 #### Segmentation evaluation result over all segmentations RMSE = np.sqrt(np.sum((refer_wat_mean_opt[1] - refer_seg[:,1])**2,axis=1)/(refer_wat_mean_opt.shape[1])) pred_seg = RMSE > th_res #Apply threshold comp_seg = np.logical_not(np.logical_xor(pred_seg,lab_seg)) #Comparation method result with true labels acc_p = np.sum(comp_seg)/(1.0*len(comp_seg)) print "Final accuracy on pixel-based {} segmentations: {}".format(len(comp_seg),acc_p)
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 file (/opt/ros_hadoop/master/dist/HMB_4.bag) in the HDFS under /user/root/ bash hdfs dfs -put /opt/ros_hadoop/master/dist/HMB_4.bag hdfs dfs -ls Process the ros bag file in Spark using the RosbagInputFormat Create the Spark Session or get an existing one
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.builder.config(conf=sparkConf).getOrCreate() sc = spark.sparkContext
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.chunkIdx":"/opt/ros_hadoop/master/dist/HMB_4.bag.idx.bin"})
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 implementations will be given. Collect the connections from all Spark partitions of the bag file into the Spark driver
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 specify what topic to process
%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_acceleration_covariance) i1 = Input(shape=(3,)) i2 = Input(shape=(3,)) o = dot([i1,i2], axes=1) model = Model([i1,i2], o) # return a tuple with (numpy dot product, keras dot "predict") return ( np.dot(linear_acceleration_covariance.reshape(3,3), [linear_acceleration['x'], linear_acceleration['y'], linear_acceleration['z']]), model.predict([ np.array([[ linear_acceleration['x'], linear_acceleration['y'], linear_acceleration['z'] ]]), linear_acceleration_covariance.reshape((3,3))]) ) fin.flatMap(partial(msg_map, func=f, conn=conn_d['/vehicle/imu/data_raw'])).take(5) # tuple with (numpy dot product, keras dot "predict")
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 feature is a feature that does not express a continuous quantity, but rather takes on one of a set of fixed values. Most deep learning models express these feature by turning them into high-dimensional vectors. During model training, the value of that vector is adjusted to help the model predict its objective better. For example, suppose that our goal is to predict which user is going to watch which movie. To do that, we represent each user and each movie by an embedding vector. Initially, these embeddings will take on random values - but during training, we will adjust them so that embeddings of users and the movies they watch end up closer together. Taking raw categorical features and turning them into embeddings is normally a two-step process: Firstly, we need to translate the raw values into a range of contiguous integers, normally by building a mapping (called a "vocabulary") that maps raw values ("Star Wars") to integers (say, 15). Secondly, we need to take these integers and turn them into embeddings. Defining the vocabulary The first step is to define a vocabulary. We can do this easily using Keras preprocessing layers.
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 features that have not been seen during vocabulary construction. Using feature hashing In fact, the StringLookup layer allows us to configure multiple OOV indices. If we do that, any raw value that is not in the vocabulary will be deterministically hashed to one of the OOV indices. The more such indices we have, the less likley it is that two different raw feature values will hash to the same OOV index. Consequently, if we have enough such indices the model should be able to train about as well as a model with an explicit vocabulary without the disadvantage of having to maintain the token list. We can take this to its logical extreme and rely entirely on feature hashing, with no vocabulary at all. This is implemented in the tf.keras.layers.experimental.preprocessing.Hashing layer.
# 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