├── code
├── README
├── users_dataset.py
├── fully_connected.py
├── encoder_rnn.py
├── decoder_rnn.py
├── words_clustering.py
├── confusion_matrix_analysis.py
├── run_encoder.py
├── train_denoising_autoencoder.py
├── data_loading_preprocessing.py
├── plot_autoencoder.py
├── Bhattacharyya_distance.py
├── users_identification.py
└── users_disambiguation.py
├── plots
└── README
├── outputs
└── README
├── input_files
└── README
├── processed_files
└── README
├── model_parameters
└── README
├── README.md
└── LICENSE
/code/README:
--------------------------------------------------------------------------------
1 | Folder with the source code files.
2 |
--------------------------------------------------------------------------------
/plots/README:
--------------------------------------------------------------------------------
1 | Folder in which the plots will be saved.
2 |
--------------------------------------------------------------------------------
/outputs/README:
--------------------------------------------------------------------------------
1 | Folder in which the output files will be saved.
2 |
--------------------------------------------------------------------------------
/input_files/README:
--------------------------------------------------------------------------------
1 | Folder in which the input files have to be saved.
2 |
--------------------------------------------------------------------------------
/processed_files/README:
--------------------------------------------------------------------------------
1 | Folder in which the processed files will be saved.
2 |
--------------------------------------------------------------------------------
/model_parameters/README:
--------------------------------------------------------------------------------
1 | Folder in which the the framework parameters will be saved.
2 |
--------------------------------------------------------------------------------
/code/users_dataset.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | users_dataset: defines the dataset structure for the autoencoder
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | from torch.utils.data import Dataset
23 |
24 |
25 | class UsersDatasetAutoencoder(Dataset):
26 |
27 | def __init__(self, input_list):
28 | self.sentences = input_list
29 |
30 | def __len__(self):
31 | return len(self.sentences)
32 |
33 | def __getitem__(self, idx):
34 | sample = self.sentences[idx]
35 | return sample
36 |
--------------------------------------------------------------------------------
/code/fully_connected.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | fully_connected: defines a fully connected layer with tanh activation function
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import torch
23 | import torch.nn as nn
24 |
25 |
26 | class FullyConnected(nn.Module):
27 | def __init__(self, hidden_size):
28 | super(FullyConnected, self).__init__()
29 | self.fc = nn.Linear(hidden_size, hidden_size)
30 | self.tan = nn.Tanh()
31 |
32 | def forward(self, x):
33 | x = torch.transpose(x, 0, 1)
34 | connect = self.fc(x)
35 | connect = self.tan(connect)
36 | connect = torch.transpose(connect, 0, 1)
37 | return connect
38 |
--------------------------------------------------------------------------------
/code/encoder_rnn.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | encoder: defines the architecture of the GRU-based RNN encoder
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import torch.nn as nn
23 |
24 |
25 | class RNNEncoder(nn.Module):
26 | def __init__(self, hidden_size, num_layers):
27 | super(RNNEncoder, self).__init__()
28 | self.hidden_size = hidden_size
29 | self.num_layers = num_layers
30 | self.encoder = nn.GRU(1, hidden_size, num_layers)
31 | self.drop = nn.Dropout(p=0.2)
32 |
33 | def encode(self, x):
34 | _, hidden = self.encoder(x)
35 | hidden = self.drop(hidden)
36 | return hidden
37 |
38 | def forward(self, x):
39 | hidden = self.encode(x)
40 | return hidden
41 |
--------------------------------------------------------------------------------
/code/decoder_rnn.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | decoder_rnn: defines the architecture of the GRU-based RNN decoder
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import torch
23 | import torch.nn as nn
24 | from torch.nn.utils.rnn import pad_packed_sequence
25 |
26 |
27 | class RNNDecoder(nn.Module):
28 | def __init__(self, hidden_size, num_layers):
29 | super(RNNDecoder, self).__init__()
30 | self.hidden_size = hidden_size
31 | self.num_layers = num_layers
32 | self.decoder = nn.GRU(1, hidden_size, num_layers)
33 | self.lin = nn.Linear(hidden_size, 1)
34 |
35 | def decode(self, x, hidden):
36 | decoder_output, hidden = self.decoder(x, hidden)
37 | decoder_output = pad_packed_sequence(decoder_output, batch_first=True)[0]
38 | decoder_output = torch.transpose(decoder_output, 0, 1)
39 | decoder_output = self.lin(decoder_output)
40 | decoder_output = torch.transpose(decoder_output, 0, 1)
41 | return decoder_output, hidden
42 |
43 | def forward(self, x, hidden):
44 | output, hidden = self.decode(x, hidden)
45 | return output, hidden
46 |
--------------------------------------------------------------------------------
/code/words_clustering.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | sentences_clustering: clusters the codes into classes using the GMM-based clustering algorithm
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib.pyplot as plt
25 | from sklearn.mixture import BayesianGaussianMixture
26 | import pickle
27 | plt.switch_backend('agg')
28 |
29 | if __name__ == '__main__':
30 | parser = argparse.ArgumentParser(description=__doc__)
31 | parser.add_argument('num_clusters', help='Number of classes for clustering', type=int)
32 | args = parser.parse_args()
33 |
34 | num_traces = 40
35 |
36 | # ---------------------------------------------------------------------------------------------------------------- #
37 | # SENTENCES CLUSTERING #
38 |
39 | hidden_sentences = []
40 | lengths = []
41 | for idx in range(num_traces):
42 | with open('../processed_files/hiddens_train_user' + str(idx) + '.txt',
43 | "rb") as fp: # Unpickling
44 | sentences_train = pickle.load(fp)
45 | hidden_sentences.extend(sentences_train.cpu().data.numpy())
46 | lengths.append(len(sentences_train))
47 |
48 | hidden_sentences = np.asarray(hidden_sentences)
49 | lengths = np.asarray(lengths)
50 |
51 | sentences = hidden_sentences
52 |
53 | num_clusters = args.num_clusters
54 | gauss = BayesianGaussianMixture(n_components=num_clusters, covariance_type='diag', max_iter=200).fit(
55 | sentences)
56 |
57 | with open('../processed_files/gauss.txt', "wb") as fp: # Pickling
58 | pickle.dump(gauss, fp)
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Smartphone identification via passive traffic fingerprinting
2 | This repository contains the reference code for the paper [''Smartphone Identification via Passive Traffic Fingerprinting: a Sequence-to-Sequence Learning Approach'' DOI: 10.1109/MNET.001.1900101](https://ieeexplore.ieee.org/document/9003304).
3 |
4 | If you find the project useful and you use this code, please cite our paper:
5 | ```
6 | @article{Meneghello2020Network,
7 | author={Francesca Meneghello and Michele Rossi and Nicola Bui},
8 | title={Smartphone Identification via Passive Traffic Fingerprinting: a Sequence-to-Sequence Learning Approach},
9 | journal={IEEE Network},
10 | volume={34},
11 | number={2},
12 | pages={112--120},
13 | year={2020}
14 | }
15 | ```
16 |
17 | # How to use
18 | Clone the repository and enter the folder with the python code:
19 | ```bash
20 | cd
21 | git clone https://github.com/francescamen/smartphone_identification
22 | cd code
23 | ```
24 |
25 | Download the input data from http://researchdata.cab.unipd.it/id/eprint/292, unzip and put them into the ```input_files``` folder.
26 |
27 | ## Train and test the framework
28 | To create the smartphone fingerprints and uses them to correctly associate unknown traffic traces to the user labels execute the following commands:
29 | ```bash
30 | python data_loading_preprocessing.py
31 | python train_denoising_autoencoder.py
32 | python run_encoder.py
33 | python words_clustering.py
34 | python users_identification.py
35 | ```
36 | ## Visualize the results
37 | In the ```code``` folder you can find other utilities functions.
38 | To visualize the performance of the autoencoder run the following command:
39 | ```bash
40 | python plot_autoencoder.py
41 | ```
42 | The confusion matrix can be computed and plotted throught the command:
43 | ```bash
44 | python confusion_matrix_analysis.py
45 | ```
46 | The users similarity assessment is performed by executing the following commands:
47 | ```bash
48 | python users_disambiguation.py
49 | python Bhattacharyya_distance.py
50 | ```
51 |
52 | ## Parameters
53 | The results on the article are obtained with the following parameters: ```=32``` ```=2``` ```=100``` ```=50``` ```=100```.
54 |
55 | # Authors
56 | Francesca Meneghello, Michele Rossi, Nicola Bui
57 |
58 | # Contact
59 | meneghello@dei.unipd.it
60 | github.com/francescamen
61 |
--------------------------------------------------------------------------------
/code/confusion_matrix_analysis.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | confusion_matrix_analysis: computes the confusion matrices
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import numpy as np
23 | import matplotlib.pyplot as plt
24 |
25 | if __name__ == '__main__':
26 |
27 | confusion_matrix = np.load('../outputs/confusion_matrix_test.npy')
28 |
29 | number_users = confusion_matrix.shape[0]
30 |
31 | precision = np.zeros((number_users, 1))
32 | recall = np.zeros((number_users, 1))
33 | f_score = np.zeros((number_users, 1))
34 | true_positive = np.diag(confusion_matrix)
35 | false_positive = np.sum(confusion_matrix, axis=0) - true_positive
36 | false_negative = np.sum(confusion_matrix, axis=1) - true_positive
37 | for user in range(1, number_users + 1):
38 | if true_positive[user - 1] > 0:
39 | precision[user - 1] = true_positive[user - 1] / (true_positive[user - 1] + false_positive[user - 1])
40 | recall[user - 1] = true_positive[user - 1] / (true_positive[user - 1] + false_negative[user - 1])
41 | f_score[user - 1] = 2 * precision[user - 1] * recall[user - 1] / (precision[user - 1] + recall[user - 1])
42 | else:
43 | precision[user - 1] = 0
44 | recall[user - 1] = 0
45 | f_score[user - 1] = 0
46 |
47 | f_score_mean = np.mean(f_score)
48 |
49 | confusion_matrix_normaliz_row = confusion_matrix / np.sum(confusion_matrix, axis=1).reshape(-1, 1)
50 | confusion_matrix_normaliz_column = \
51 | confusion_matrix_normaliz_row / np.sum(confusion_matrix_normaliz_row, axis=0).reshape(1, -1)
52 | max_columns = np.amax(confusion_matrix_normaliz_column, axis=0)
53 | sum_max_columns = np.sum(max_columns)
54 |
55 | correct_windows = np.sum(np.diag(confusion_matrix))
56 | number_windows = np.sum(np.sum(confusion_matrix, 1))
57 | perc_correct_window = correct_windows/number_windows * 100
58 | print('perc_correct_windows: ' + str(perc_correct_window))
59 |
60 | confusion_matrix_majority = np.zeros(confusion_matrix_normaliz_row.shape)
61 | correct = 0
62 | for r in range(0, confusion_matrix_normaliz_row.shape[0]):
63 | index_max = np.argmax(confusion_matrix_normaliz_row[r, :])
64 | val_max = np.max(confusion_matrix_normaliz_row[r, :])
65 | indices_maxs = [i for i, j in enumerate(confusion_matrix_normaliz_row[r, :]) if j == val_max]
66 | confusion_matrix_majority[r, indices_maxs] = 1/len(indices_maxs)
67 | if index_max == r and len(indices_maxs) == 1:
68 | correct = correct + 1
69 | perc_correct_user = correct/number_users * 100
70 | print('perc_correct_users: ' + str(perc_correct_user))
71 |
72 | fig, axes = plt.subplots(nrows=1, ncols=2)
73 | fig.set_size_inches(12, 5)
74 | ax = axes.flat
75 |
76 | im1 = ax[0].pcolor(np.linspace(0.5, number_users + 0.5, number_users + 1),
77 | np.linspace(0.5, number_users + 0.5, number_users + 1),
78 | np.transpose(confusion_matrix_normaliz_row),
79 | cmap='Blues', edgecolors='black', vmin=0, vmax=1)
80 | ax[0].set_title(r"$\bf{" + "Normalized" + "}$" + " " r"$\bf{" + "confusion" + "}$" + " " r"$\bf{" + "matrix" + "}$",
81 | FontSize=14)
82 | ax[0].set_xlabel('Actual user', FontSize=14)
83 | ax[0].set_xticks(np.linspace(1, number_users, number_users), minor=True)
84 | ax[0].set_yticks(np.linspace(1, number_users, number_users), minor=True)
85 | ax[0].set_ylabel('Predicted user', FontSize=14)
86 | ax[0].tick_params(axis="x", labelsize=11)
87 | ax[0].tick_params(axis="y", labelsize=11)
88 |
89 | im2 = ax[1].pcolor(np.linspace(0.5, number_users + 0.5, number_users + 1),
90 | np.linspace(0.5, number_users + 0.5, number_users + 1), np.transpose(confusion_matrix_majority),
91 | cmap='Blues', edgecolors='black', vmin=0, vmax=1)
92 |
93 | ax[1].set_title(r"$\bf{" + "Majority" + "}$" + " " r"$\bf{" + "score" + "}$", FontSize=14)
94 | ax[1].set_xlabel('Actual user', FontSize=14)
95 | ax[1].set_xticks(np.linspace(1, number_users, number_users), minor=True)
96 | ax[1].set_yticks(np.linspace(1, number_users, number_users), minor=True)
97 | ax[1].set_ylabel('Predicted user', FontSize=14)
98 | ax[1].tick_params(axis="x", labelsize=11)
99 | ax[1].tick_params(axis="y", labelsize=11)
100 |
101 | fig.subplots_adjust(right=0.88)
102 | cbar_ax = fig.add_axes([0.90, 0.15, 0.02, 0.7])
103 | cbar = fig.colorbar(im1, cax=cbar_ax)
104 | cbar.ax.set_ylabel('Accuracy', FontSize=14)
105 | cbar.ax.tick_params(axis="y", labelsize=11)
106 |
107 | plt.savefig('../plots/cm_total.eps')
108 |
109 | plt.show()
110 |
--------------------------------------------------------------------------------
/code/run_encoder.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | run_encoder: outputs the code for each input word using the GRU-based RNN encoder
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib.pyplot as plt
25 | import torch
26 | from encoder_rnn import RNNEncoder
27 | from fully_connected import FullyConnected
28 | from decoder_rnn import RNNDecoder
29 | import pickle
30 | plt.switch_backend('agg')
31 | device = torch.device("cuda")
32 |
33 |
34 | def tensor_from_sentence(sentence):
35 | sent_list = list(sentence)
36 | return torch.tensor(sent_list).view(-1, 1).float()
37 |
38 |
39 | if __name__ == '__main__':
40 | parser = argparse.ArgumentParser(description=__doc__)
41 | parser.add_argument('hidden_neurons', help='Number of hidden neurons', type=int)
42 | parser.add_argument('layers', help='Number of layers', type=int)
43 | args = parser.parse_args()
44 |
45 | num_traces = 40
46 |
47 | with open('../processed_files/mInfo_train.txt', "rb") as fp: # Unpickling
48 | mInfo_train = pickle.load(fp)
49 | with open('../processed_files/mInfo_test.txt', "rb") as fp: # Unpickling
50 | mInfo_test = pickle.load(fp)
51 |
52 | with open('../processed_files/mTime_train.txt', "rb") as fp: # Unpickling
53 | mTime_train = pickle.load(fp)
54 | with open('../processed_files/mTime_test.txt', "rb") as fp: # Unpickling
55 | mTime_test = pickle.load(fp)
56 |
57 | with open('../processed_files/sentences_train.txt', "rb") as fp: # Unpickling
58 | sentences_train = pickle.load(fp)
59 | with open('../processed_files/sentences_test.txt', "rb") as fp: # Unpickling
60 | sentences_test = pickle.load(fp)
61 |
62 | # ---------------------------------------------------------------------------------------------------------------- #
63 | # CODE THE SENTENCES #
64 |
65 | encoder_model = RNNEncoder(args.hidden_neurons, args.layers).to(device)
66 | fully_connect = FullyConnected(args.hidden_neurons).to(device)
67 |
68 | encoder_model.load_state_dict(torch.load('../model_parameters/encoder_model_' + str(num_traces) + '.pt'))
69 | fully_connect.load_state_dict(torch.load('../model_parameters/fully_connected_' + str(num_traces) + '.pt'))
70 |
71 | encoder_model.eval()
72 | fully_connect.eval()
73 |
74 | mTime_train = np.asarray(mTime_train)
75 | mTime_test = np.asarray(mTime_test)
76 | mInfo_train = np.asarray(mInfo_train)
77 | mInfo_test = np.asarray(mInfo_test)
78 |
79 | for trace in range(num_traces):
80 | indices = np.argwhere(mInfo_train[:, 7] == trace + 1)[:, 0]
81 | sentences_single_user_train = sentences_train[indices[0]:indices[-1]]
82 |
83 | hiddens = torch.zeros((len(sentences_single_user_train), args.hidden_neurons*args.layers), device=device)
84 | for i_w in range(len(sentences_single_user_train)):
85 | x_input = tensor_from_sentence(sentences_single_user_train[i_w])
86 | x_input = torch.reshape(x_input, (x_input.shape[0], 1, 1)).to(device)
87 | representation = fully_connect(encoder_model(x_input))
88 | representation = torch.transpose(representation, 0, 1).contiguous().to(device)
89 | representation = representation.view(1, -1)
90 | hiddens[i_w, :] = representation
91 |
92 | with open('../processed_files/hiddens_train_user' + str(trace) + '.txt', "wb") as fp: # Pickling
93 | pickle.dump(hiddens, fp)
94 | with open('../processed_files/times_train_user' + str(trace) + '.txt', "wb") as fp: # Pickling
95 | pickle.dump(mTime_train[indices[0]:indices[-1], :], fp)
96 |
97 | indices = np.argwhere(mInfo_test[:, 7] == trace + 1)[:, 0]
98 | sentences_single_user_test = sentences_test[indices[0]:indices[-1]]
99 |
100 | hiddens = torch.zeros((len(sentences_single_user_test), args.hidden_neurons*args.layers))
101 | for i_w in range(len(sentences_single_user_test)):
102 | x_input = tensor_from_sentence(sentences_single_user_test[i_w])
103 | x_input = torch.reshape(x_input, (x_input.shape[0], 1, 1)).to(device)
104 | representation = fully_connect(encoder_model(x_input))
105 | representation = torch.transpose(representation, 0, 1).contiguous().to(device)
106 | representation = representation.view(1, -1)
107 | hiddens[i_w, :] = representation
108 |
109 | with open('../processed_files/hiddens_test_user' + str(trace) + '.txt', "wb") as fp: # Pickling
110 | pickle.dump(hiddens, fp)
111 | with open('../processed_files/times_test_user' + str(trace) + '.txt', "wb") as fp: # Pickling
112 | pickle.dump(mTime_test[indices[0]:indices[-1], :], fp)
113 |
--------------------------------------------------------------------------------
/code/train_denoising_autoencoder.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | train_denoising_autoencoder: trains the autoencoder and save the coding network parameters
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib.pyplot as plt
25 | import torch
26 | import torch.nn as nn
27 | import torch.optim as optim
28 | from torch.utils.data import DataLoader
29 | from torch.nn.utils.rnn import pack_sequence
30 | from torch.nn.utils.rnn import pad_packed_sequence
31 | from encoder_rnn import RNNEncoder
32 | from fully_connected import FullyConnected
33 | from decoder_rnn import RNNDecoder
34 | from users_dataset import UsersDatasetAutoencoder
35 | import pickle
36 | import gc
37 | plt.switch_backend('agg')
38 | device = torch.device("cuda")
39 |
40 |
41 | def tensor_from_sentence(sentence):
42 | return torch.tensor(list(sentence), device=device).view(-1, 1).float()
43 |
44 |
45 | def collate_fn_autoencoder(_list):
46 | _list.sort(key=len, reverse=True)
47 | return _list
48 |
49 |
50 | def collate_fn(_list):
51 | return _list
52 |
53 |
54 | def input_packing(_list):
55 | tensor_list = [tensor_from_sentence(_list[i]) for i in range(len(_list))]
56 | return pack_sequence(tensor_list)
57 |
58 |
59 | def target_packing(_list):
60 | tensor_list = [tensor_from_sentence(torch.cat((torch.zeros((1,), device=device), _list[i][:-1, 0]), 0)) for i in
61 | range(len(_list))]
62 | packed_list = pack_sequence(tensor_list)
63 | return packed_list
64 |
65 |
66 | if __name__ == '__main__':
67 | parser = argparse.ArgumentParser(description=__doc__)
68 | parser.add_argument('hidden_neurons', help='Number of hidden neurons', type=int)
69 | parser.add_argument('layers', help='Number of layers', type=int)
70 | parser.add_argument('epochs', help='Number of epochs', type=int)
71 | args = parser.parse_args()
72 |
73 | num_traces = 40
74 |
75 | with open('../processed_files/sentences_train.txt', "rb") as fp: # Unpickling
76 | sentences_train = pickle.load(fp)
77 | with open('../processed_files/sentences_test.txt', "rb") as fp: # Unpickling
78 | sentences_test = pickle.load(fp)
79 |
80 | # ---------------------------------------------------------------------------------------------------------------- #
81 | # AUTOENCODER #
82 |
83 | encoder_model = RNNEncoder(args.hidden_neurons, args.layers).to(device)
84 | fully_connect = FullyConnected(args.hidden_neurons).to(device)
85 | decoder_model = RNNDecoder(args.hidden_neurons, args.layers).to(device)
86 |
87 | print(encoder_model)
88 | print(fully_connect)
89 | print(decoder_model)
90 |
91 | criterion = nn.L1Loss(reduction='none')
92 | criterion_val = nn.L1Loss()
93 |
94 | parameters_dictionary = list(encoder_model.parameters()) + list(fully_connect.parameters()) + \
95 | list(decoder_model.parameters())
96 |
97 | optimizer = optim.Adam(parameters_dictionary, lr=0.001)
98 |
99 | tensor_sentences_train = [tensor_from_sentence(sentences_train[i]) for i in range(len(sentences_train))]
100 | users_dataset_train = UsersDatasetAutoencoder(tensor_sentences_train)
101 |
102 | tensor_sentences_test = [tensor_from_sentence(sentences_test[i]) for i in range(len(sentences_test))]
103 | users_dataset_test = UsersDatasetAutoencoder(tensor_sentences_test)
104 |
105 | batch_size = 64
106 | train_loader = DataLoader(users_dataset_train, batch_size=batch_size, shuffle=True, num_workers=0,
107 | collate_fn=collate_fn_autoencoder)
108 |
109 | test_loader = DataLoader(users_dataset_test, batch_size=batch_size, shuffle=True, num_workers=0,
110 | collate_fn=collate_fn_autoencoder)
111 |
112 | max_epochs = args.epochs
113 | print_loss_total = 0
114 | print_every = 500
115 | print_every_val = 50
116 | iteration = 0
117 | for epoch in range(max_epochs):
118 | print('----epoch ' + str(epoch) + ' training----')
119 | for i_batch, sample_batched in enumerate(train_loader):
120 | iteration += 1
121 | x_input = input_packing(sample_batched)
122 | x_target = target_packing(sample_batched).to(device)
123 |
124 | erasure_prob = 0.1
125 | sample_batched_noise = []
126 | for ii in range(len(sample_batched)):
127 | random_mask_array = np.random.random(sample_batched[ii].shape[0])
128 | random_mask_array = random_mask_array > erasure_prob
129 | random_mask_array = random_mask_array.astype(int)
130 | random_mask = torch.tensor(random_mask_array, device=device).float().view(-1, 1)
131 | sample_batched_noise.append(sample_batched[ii] * random_mask)
132 | x_input_noise = input_packing(sample_batched_noise).to(device)
133 |
134 | encoder_model.zero_grad()
135 | fully_connect.zero_grad()
136 | decoder_model.zero_grad()
137 |
138 | hidden = encoder_model(x_input_noise).to(device)
139 |
140 | conn = fully_connect(hidden).contiguous().to(device)
141 |
142 | out, dec_hidden = decoder_model(x_target, conn)
143 |
144 | output_unpacked = out
145 |
146 | input_unpacked = pad_packed_sequence(x_input, batch_first=True)
147 | mask = torch.clone(input_unpacked[0])
148 | mask[mask > 0] = 1
149 | output_unpacked = output_unpacked * mask
150 |
151 | loss = criterion(output_unpacked, input_unpacked[0])
152 |
153 | loss = loss
154 | loss_array = loss.data.cpu().numpy()
155 | loss_sum = torch.sum(loss, 1)
156 | lengths = input_unpacked[1].to(device)
157 | lengths_array = lengths.data.cpu().numpy()
158 | loss_mean = loss_sum[:, 0] / lengths.float()
159 | loss = torch.sum(loss_mean)
160 |
161 | loss.backward()
162 | optimizer.step()
163 |
164 | print_loss_total += loss
165 | if iteration % print_every == 0:
166 | print_loss_avg = print_loss_total / print_every
167 | print_loss_total = 0
168 | print(print_loss_avg)
169 |
170 | del x_input
171 | del x_target
172 | del out
173 | del output_unpacked
174 | del lengths
175 | del dec_hidden
176 | gc.collect()
177 |
178 | print('----epoch ' + str(epoch) + ' test----')
179 | iteration = 0
180 | print_loss_total_test = 0
181 | for i_batch, sample_batched in enumerate(test_loader):
182 | iteration += 1
183 | x_input = input_packing(sample_batched).to(device)
184 |
185 | hidden = encoder_model(x_input).to(device)
186 | conn = fully_connect(hidden).contiguous().to(device)
187 |
188 | out_list = []
189 | loss_mean_test = torch.zeros(batch_size, device=device)
190 | for bat in range(len(sample_batched)):
191 | dec_out = [torch.zeros(1, 1, 1, device=device)]
192 | out_vector = torch.zeros(sample_batched[bat].shape[0], 1, device=device)
193 | dec_hidden = conn[:, bat:bat + 1, :].contiguous()
194 | for word in range(out_vector.shape[0]):
195 | dec_out = input_packing(dec_out).to(device)
196 | out, dec_hidden = decoder_model(dec_out, dec_hidden)
197 | dec_hidden = dec_hidden.contiguous()
198 | dec_out = out.contiguous()
199 | out_vector[word] = dec_out
200 | out_list.append(out_vector)
201 | loss_mean_test[bat] = criterion_val(out_vector, sample_batched[bat])
202 | loss_mean_test_array = loss_mean_test.cpu().detach().numpy()
203 | loss_test = torch.sum(loss_mean_test)
204 |
205 | print_loss_total_test += loss_test
206 | if iteration % print_every_val == 0:
207 | print_loss_avg_test = print_loss_total_test / print_every_val
208 | print_loss_total_test = 0
209 | print(print_loss_avg_test)
210 |
211 | del out_list
212 | gc.collect()
213 |
214 | torch.save(encoder_model.state_dict(), '../model_parameters/encoder_model_' + str(num_traces) + '.pt')
215 | torch.save(decoder_model.state_dict(), '../model_parameters/decoder_model_' + str(num_traces) + '.pt')
216 | torch.save(fully_connect.state_dict(), '../model_parameters/fully_connected_' + str(num_traces) +
217 | '.pt')
218 |
--------------------------------------------------------------------------------
/code/data_loading_preprocessing.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | data_loading_preprocessing: loads the Matlab data and outputs the files to be used for further processing
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import numpy as np
23 | import matplotlib.pyplot as plt
24 | import scipy.io as sio
25 | import pickle
26 | plt.switch_backend('agg')
27 |
28 |
29 | if __name__ == '__main__':
30 | num_traces = 40
31 |
32 | # ---------------------------------------------------------------------------------------------------------------- #
33 | # FILE LOADING #
34 |
35 | # Load the Matlab files
36 | mPack_structure = sio.loadmat('../input_files/mPack.mat')
37 | mPack = mPack_structure['mPack']
38 |
39 | mTime_structure = sio.loadmat('../input_files/mTime.mat')
40 | mTime = mTime_structure['mTime']
41 |
42 | mInfo_structure = sio.loadmat('../input_files/mInfo.mat')
43 | mInfo = mInfo_structure['mInfo']
44 |
45 | validInt_struct = sio.loadmat('../input_files/validInts.mat')
46 | validInts = validInt_struct['validInts']
47 |
48 | # Order the file with respect to the absolute time, ordering inside each trace
49 | traceNum = 1
50 | mTimeSelect = []
51 | mPackSelect = []
52 | mInfoSelect = []
53 | for trace in range(1, num_traces + 1):
54 | indices = np.argwhere(mInfo[:, -1] == trace)
55 |
56 | mTime_trace = mTime[indices[:, 0], :]
57 | mPack_trace = mPack[indices[:, 0], :]
58 | mInfo_trace = mInfo[indices[:, 0], :]
59 |
60 | mInfo_trace[:, -1] = traceNum # to label each selected trace with increasing indices
61 | traceNum = traceNum + 1
62 |
63 | # concatenate all the information in a single vector in order to order all the information in the same manner
64 | array_to_be_ordered = np.zeros((mTime_trace.shape[0], mTime_trace.shape[1] + mPack_trace.shape[1] +
65 | mInfo_trace.shape[1]))
66 | array_to_be_ordered[:, 0:mTime_trace.shape[1]] = mTime_trace
67 | array_to_be_ordered[:, mTime_trace.shape[1]:mTime_trace.shape[1] + mPack_trace.shape[1]] = mPack_trace
68 | array_to_be_ordered[:, mTime_trace.shape[1] + mPack_trace.shape[1]:mTime_trace.shape[1] + mPack_trace.shape[1]
69 | + mInfo_trace.shape[1]] = mInfo_trace
70 |
71 | # order the array
72 | array_ordered = array_to_be_ordered[array_to_be_ordered[:, 1].argsort()]
73 |
74 | # extract each singular information from the vector
75 | mTime_trace = array_ordered[:, 0:mTime_trace.shape[1]]
76 | mPack_trace = array_ordered[:, mTime_trace.shape[1]:mTime_trace.shape[1] + mPack_trace.shape[1]]
77 | mInfo_trace = array_ordered[:, mTime_trace.shape[1] + mPack_trace.shape[1]:mTime_trace.shape[1]
78 | + mPack_trace.shape[1]
79 | + mInfo_trace.shape[1]]
80 |
81 | # save the information in the matrices with all the traces
82 | mTimeSelect.append(mTime_trace)
83 | mPackSelect.append(mPack_trace)
84 | mInfoSelect.append(mInfo_trace)
85 | mTime = np.vstack(mTimeSelect)
86 | mPack = np.vstack(mPackSelect)
87 | mInfo = np.vstack(mInfoSelect)
88 |
89 | # Cancel the sentences with a length smaller than threshold, deleting also all the related information
90 | # to that aim, first concatenate all the information in a single vector
91 | array = np.zeros((mTime.shape[0], mTime.shape[1] + mPack.shape[1] + mInfo.shape[1]))
92 | array[:, 0:mTime.shape[1]] = mTime
93 | array[:, mTime.shape[1]:mTime.shape[1] + mPack.shape[1]] = mPack
94 | array[:, mTime.shape[1] + mPack.shape[1]:mTime.shape[1] + mPack.shape[1] + mInfo.shape[1]] = mInfo
95 |
96 | # create a new array in which to insert only the sentences with more than threshold samples
97 | new_array = np.zeros((mTime.shape[0], mTime.shape[1] + mPack.shape[1] + mInfo.shape[1]))
98 | index = 0
99 | threshold = 6 # the words smaller than that threshold will be discarded
100 | for i in range(array.shape[0]):
101 | if (array[i, mTime.shape[1] + 2 + threshold] != 0) or (np.sum(array[i, mTime.shape[1] + 2: mTime.shape[1] + 2
102 | + threshold]) > 500):
103 | new_array[index, :] = array[i, :]
104 | index = index + 1
105 | new_array = new_array[:index, :]
106 |
107 | # Select only the patterns inside the valid intervals extracted with Matlab
108 | new_array_2 = np.zeros((new_array.shape[0], mTime.shape[1] + mPack.shape[1] + mInfo.shape[1]))
109 | index = 0
110 | for i in range(new_array.shape[0]):
111 | trace_index = int(new_array[i, mPack.shape[1] + mTime.shape[1] + mInfo.shape[1] - 1])
112 | start_valid_time = validInts[0][trace_index - 1][0, 0] + 5*60
113 | end_valid_time = validInts[0][trace_index - 1][0, 1]
114 | if end_valid_time > 37000: # cut all traces at 10 hours
115 | end_valid_time = start_valid_time + 36030
116 | if (new_array[i, 1] > start_valid_time) and (new_array[i, 1] < end_valid_time):
117 | new_array_2[index, :] = new_array[i, :]
118 | index = index + 1
119 | new_array_2 = new_array_2[:index, :]
120 |
121 | mTime_new = new_array_2[:, 0:mTime.shape[1]]
122 | mPack_new = new_array_2[:, mTime.shape[1]:mTime.shape[1] + mPack.shape[1]]
123 | mInfo_new = new_array_2[:, mTime.shape[1] + mPack.shape[1]:mTime.shape[1] + mPack.shape[1] + mInfo.shape[1]]
124 |
125 | trainFraction = 0.8
126 | sentences_train_pad = []
127 | sentences_test_pad = []
128 | mInfo_train = []
129 | mInfo_test = []
130 | mTime_train = []
131 | mTime_test = []
132 | dir_train = []
133 | dir_test = []
134 |
135 | for trace in range(1, num_traces + 1):
136 | indices = np.argwhere(mInfo_new[:, -1] == trace)
137 |
138 | mPack_trace = mPack_new[indices[:, 0], :]
139 | mInfo_trace = mInfo_new[indices[:, 0], :]
140 | mTime_trace = mTime_new[indices[:, 0], :]
141 |
142 | time_ass = mTime_trace[:, 1] - mTime_trace[0, 1]
143 | length_user_time = time_ass[-1]
144 | trLen_time = int(length_user_time*trainFraction)
145 |
146 | trLen = np.argwhere(time_ass < trLen_time)[-1, 0]
147 |
148 | sentences_train_pad.extend(mPack_trace[:trLen, 2:]/20000)
149 | sentences_test_pad.extend(mPack_trace[trLen:, 2:]/20000)
150 |
151 | mInfo_train.extend(mInfo_trace[:trLen, :])
152 | mInfo_test.extend(mInfo_trace[trLen:, :])
153 |
154 | mTime_train.extend(mTime_trace[:trLen, :])
155 | mTime_test.extend(mTime_trace[trLen:, :])
156 |
157 | dir_train.extend(mPack_trace[:trLen, 0])
158 | dir_test.extend(mPack_trace[trLen:, 0])
159 |
160 | sentences_train = []
161 | sentences_test = []
162 | for i in range(len(sentences_train_pad)):
163 | idx = np.argwhere(sentences_train_pad[i] == 0)
164 | if idx.size != 0:
165 | sentences_train.append(sentences_train_pad[i][:idx[0, 0]])
166 | else:
167 | sentences_train.append(sentences_train_pad[i])
168 |
169 | for i in range(len(sentences_test_pad)):
170 | idx = np.argwhere(sentences_test_pad[i] == 0)
171 | if idx.size != 0:
172 | sentences_test.append(sentences_test_pad[i][:idx[0, 0]])
173 | else:
174 | sentences_test.append(sentences_test_pad[i])
175 |
176 | del sentences_train_pad
177 | del sentences_test_pad
178 | del mInfo
179 | del mTime
180 | del mPack
181 | del mInfo_new
182 | del mPack_new
183 | del mTime_new
184 | del array
185 | del new_array_2
186 | del new_array
187 | del validInts
188 | del validInt_struct
189 | del mPack_structure
190 | del mInfo_structure
191 | del mTime_structure
192 |
193 | with open('../processed_files/mInfo_train.txt', "wb") as fp: # Pickling
194 | pickle.dump(mInfo_train, fp)
195 | with open('../processed_files/mInfo_test.txt', "wb") as fp: # Pickling
196 | pickle.dump(mInfo_test, fp)
197 |
198 | with open('../processed_files/mTime_train.txt', "wb") as fp: # Pickling
199 | pickle.dump(mTime_train, fp)
200 | with open('../processed_files/mTime_test.txt', "wb") as fp: # Pickling
201 | pickle.dump(mTime_test, fp)
202 |
203 | with open('../processed_files/sentences_train.txt', "wb") as fp: # Pickling
204 | pickle.dump(sentences_train, fp)
205 | with open('../processed_files/sentences_test.txt', "wb") as fp: # Pickling
206 | pickle.dump(sentences_test, fp)
207 |
--------------------------------------------------------------------------------
/code/plot_autoencoder.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | plot_autoencoder: tests the autoencoder performance and plots the results
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib
25 | import matplotlib.pyplot as plt
26 | import torch
27 | from torch.utils.data import DataLoader
28 | from torch.nn.utils.rnn import pack_sequence
29 | from torch.nn.utils.rnn import pad_sequence
30 | from encoder_rnn import RNNEncoder
31 | from fully_connected import FullyConnected
32 | from decoder_rnn import RNNDecoder
33 | from users_dataset import UsersDatasetAutoencoder
34 | import matplotlib.gridspec as gridspec
35 | import pickle
36 | matplotlib.use('TkAgg')
37 |
38 |
39 | def tensor_from_sentence(sentence):
40 | sent_list = list(sentence)
41 | return torch.tensor(sent_list).view(-1, 1).float()
42 |
43 |
44 | def collate_fn(_list):
45 | _list.sort(key=lambda x: x[0].shape[0], reverse=True)
46 | return _list
47 |
48 |
49 | def input_packing(_list):
50 | tensor_list = [tensor_from_sentence(_list[i]) for i in range(len(_list))]
51 | packed_list = pack_sequence(tensor_list)
52 | return packed_list
53 |
54 |
55 | if __name__ == '__main__':
56 | parser = argparse.ArgumentParser(description=__doc__)
57 | parser.add_argument('hidden_neurons', help='Number of hidden neurons', type=int)
58 | parser.add_argument('layers', help='Number of layers', type=int)
59 | args = parser.parse_args()
60 |
61 | num_traces = 40
62 |
63 | with open('../processed_files/mInfo_train.txt', "rb") as fp: # Unpickling
64 | mInfo_train = pickle.load(fp)
65 | with open('../processed_files/mInfo_test.txt', "rb") as fp: # Unpickling
66 | mInfo_test = pickle.load(fp)
67 |
68 | with open('../processed_files/mTime_train.txt', "rb") as fp: # Unpickling
69 | mTime_train = pickle.load(fp)
70 | with open('../processed_files/mTime_test.txt', "rb") as fp: # Unpickling
71 | mTime_test = pickle.load(fp)
72 |
73 | with open('../processed_files/sentences_train.txt', "rb") as fp: # Unpickling
74 | sentences_train = pickle.load(fp)
75 | with open('../processed_files/sentences_test.txt', "rb") as fp: # Unpickling
76 | sentences_test = pickle.load(fp)
77 | encoder_model = RNNEncoder(args.hidden_neurons, args.layers)
78 | fully_connect = FullyConnected(args.hidden_neurons)
79 | decoder_model = RNNDecoder(args.hidden_neurons, args.layers)
80 |
81 | encoder_model.load_state_dict(torch.load('../model_parameters/encoder_model_' + str(num_traces) + '.pt'))
82 | fully_connect.load_state_dict(torch.load('../model_parameters/fully_connected_' + str(num_traces) + '.pt'))
83 | decoder_model.load_state_dict(torch.load('../model_parameters/decoder_model_' + str(num_traces) + '.pt'))
84 |
85 | tensor_sentences_train = [[tensor_from_sentence(sentences_train[i]), tensor_from_sentence(mInfo_train[i][7:8] - 1),
86 | tensor_from_sentence(mTime_train[i])] for i in range(len(sentences_train))]
87 | users_dataset_train = UsersDatasetAutoencoder(tensor_sentences_train)
88 |
89 | tensor_sentences_test = [[tensor_from_sentence(sentences_test[i]),
90 | tensor_from_sentence(mInfo_test[i][7:8] - 1),
91 | tensor_from_sentence(mTime_test[i])] for i in range(len(sentences_test))]
92 | users_dataset_test = UsersDatasetAutoencoder(tensor_sentences_test)
93 |
94 | batch_size = 1
95 | train_loader = DataLoader(users_dataset_train, batch_size=batch_size, shuffle=False, num_workers=0,
96 | collate_fn=collate_fn)
97 |
98 | test_loader = DataLoader(users_dataset_test, batch_size=batch_size, shuffle=False, num_workers=0,
99 | collate_fn=collate_fn)
100 |
101 | fig = plt.figure(1)
102 | gridspec.GridSpec(2, 1)
103 | plt.subplot2grid((2, 1), (0, 0))
104 |
105 | index_last = 0
106 | for i in range(50, 60):
107 | sample_batched = [users_dataset_test[i]]
108 | sample_batched_sent = [sample_batched[i][0] for i in range(len(sample_batched))]
109 | if sample_batched_sent[0].shape[0] > 0:
110 | sample_batched_labels = [sample_batched[i][1] for i in range(len(sample_batched))]
111 | sample_batched_time = [sample_batched[i][2][1] for i in range(len(sample_batched))]
112 | sample_batched_duration = [sample_batched[i][2][0]*10 for i in range(len(sample_batched))]
113 |
114 | sample_batched_sent = torch.stack(sample_batched_sent)
115 | sample_batched_sent = torch.transpose(sample_batched_sent, 0, 1)
116 | x_input = sample_batched_sent
117 | x_input = torch.reshape(x_input, (x_input.shape[0], 1, 1))
118 | hidden_layer = fully_connect(encoder_model(x_input))
119 | representation = torch.transpose(hidden_layer, 0, 1)
120 | representation = representation.view(1, -1)
121 |
122 | dec_out = [torch.zeros(1, 1, 1)]
123 | out_vector = torch.zeros(sample_batched_sent.shape[0], 1)
124 | dec_hidden = hidden_layer[:, :, :]
125 | for word in range(out_vector.shape[0]):
126 | dec_out = input_packing(dec_out)
127 | out, dec_hidden = decoder_model(dec_out, dec_hidden)
128 | dec_out = out
129 | out_vector[word] = dec_out
130 |
131 | out_vector_array = pad_sequence(out_vector).data[0].numpy()
132 | x_input_array = x_input.data.numpy()[:, 0, 0]
133 |
134 | x_ax = np.linspace(index_last,
135 | out_vector_array.shape[0] + index_last,
136 | out_vector_array.shape[0])
137 | index_last = index_last + out_vector_array.shape[0]
138 |
139 | plt.plot(x_ax, out_vector_array*20000, c='firebrick', marker='x', linestyle='--', markersize=3,
140 | linewidth=0.8)
141 | plt.plot(x_ax, x_input_array*20000, c='midnightblue', marker='o', markersize=3, linewidth=0.8)
142 | plt.axvline(x=index_last + 1, color='k', linewidth=2, linestyle='--')
143 | index_last = index_last + 1 + 1
144 | plt.grid()
145 | plt.legend(('predicted', 'actual'), loc='upper right')
146 | plt.ylabel('Character value', FontSize=12)
147 | plt.xlabel('Word time slot', FontSize=12)
148 | plt.xticks(FontSize=12)
149 | plt.yticks(FontSize=12)
150 |
151 | plt.subplot2grid((2, 1), (1, 0))
152 | index_last = 0
153 | for i in range(900, 910):
154 | sample_batched = [users_dataset_test[i]]
155 | sample_batched_sent = [sample_batched[i][0] for i in range(len(sample_batched))]
156 | if sample_batched_sent[0].shape[0] > 0:
157 | sample_batched_labels = [sample_batched[i][1] for i in range(len(sample_batched))]
158 | sample_batched_time = [sample_batched[i][2][1] for i in range(len(sample_batched))]
159 | sample_batched_duration = [sample_batched[i][2][0]*10 for i in range(len(sample_batched))]
160 |
161 | sample_batched_sent = torch.stack(sample_batched_sent)
162 | sample_batched_sent = torch.transpose(sample_batched_sent, 0, 1)
163 | x_input = sample_batched_sent
164 | x_input_array = x_input.data.numpy()
165 | x_input = torch.reshape(x_input, (x_input.shape[0], 1, 1))
166 | hidden_layer = fully_connect(encoder_model(x_input))
167 | representation = torch.transpose(hidden_layer, 0, 1)
168 | representation = representation.view(1, -1)
169 | representation_array = representation.data.numpy()
170 |
171 | dec_out = [torch.zeros(1, 1, 1)]
172 | out_vector = torch.zeros(sample_batched_sent.shape[0], 1)
173 | dec_hidden = hidden_layer[:, :, :]
174 | for word in range(out_vector.shape[0]):
175 | dec_out = input_packing(dec_out)
176 | out, dec_hidden = decoder_model(dec_out, dec_hidden)
177 | dec_out = out
178 | out_vector[word] = dec_out
179 |
180 | out_vector_array = pad_sequence(out_vector).data[0].numpy()
181 | x_input_array = x_input.data.numpy()[:, 0, 0]
182 |
183 | x_ax = np.linspace(index_last,
184 | out_vector_array.shape[0] + index_last,
185 | out_vector_array.shape[0])
186 | index_last = index_last + out_vector_array.shape[0]
187 |
188 | mk = matplotlib.markers.MarkerStyle(marker='.', fillstyle='none')
189 | plt.plot(x_ax, out_vector_array*20000, c='firebrick', marker='x', linestyle='--', markersize=3,
190 | linewidth=0.8)
191 | plt.plot(x_ax, x_input_array*20000, c='midnightblue', marker='o', markersize=3, linewidth=0.8)
192 | plt.axvline(x=index_last + 1, color='k', linewidth=2, linestyle='--')
193 | index_last = index_last + 1 + 1
194 | plt.grid()
195 | plt.legend(('predicted', 'actual'), loc='upper right')
196 | plt.ylabel('Character value', FontSize=12)
197 | plt.xlabel('Word time slot', FontSize=12)
198 | plt.xticks(FontSize=12)
199 | plt.yticks(FontSize=12)
200 |
201 | fig.tight_layout()
202 | fig.set_size_inches(w=11, h=4)
203 | fig.savefig('../plots/autoencoder_multiple.eps')
204 |
--------------------------------------------------------------------------------
/code/Bhattacharyya_distance.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | Battacharyya_distance: computes distance metrics
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib
25 | import matplotlib.pyplot as plt
26 | import math as mt
27 | import pickle
28 | import matplotlib.gridspec as gridspec
29 | import scipy.io as sio
30 | matplotlib.use('TkAgg')
31 | plt.switch_backend('agg')
32 |
33 | if __name__ == '__main__':
34 | parser = argparse.ArgumentParser(description=__doc__)
35 | parser.add_argument('num_clusters', help='Number of classes for clustering', type=int)
36 | args = parser.parse_args()
37 |
38 | num_traces = 40
39 |
40 | num_clusters = args.num_clusters
41 | compute_pdf = True
42 |
43 | if compute_pdf:
44 | # CLUSTERING
45 | with open('../processed_files/gauss.txt', "rb") as fp: # Unpickling
46 | gauss = pickle.load(fp)
47 |
48 | # COMPUTE THE USERS PDF ON THE TRAINING DATA
49 | winLen = 3000
50 | winStep = 30
51 | users_pdf = np.zeros((num_traces, num_clusters))
52 |
53 | for idx in range(num_traces):
54 | with open('../processed_files/hiddens_train_user' + str(idx) + '.txt',
55 | "rb") as fp: # Unpickling
56 | sentences = pickle.load(fp)
57 | with open('../processed_files/times_train_user' + str(idx) + '.txt',
58 | "rb") as fp: # Unpickling
59 | time = pickle.load(fp)
60 |
61 | time[:, 1] = time[:, 1] - time[0, 1]
62 | end = time[-1, 1]
63 | num_groups = int(mt.ceil((end - winLen) / winStep))
64 | frequency_vector = np.zeros((num_groups, num_clusters))
65 | for i in range(num_groups):
66 | new_start = min(list(time[:, 1]), key=lambda x: abs(x - i * winStep))
67 | new_end = min(list(time[:, 1]), key=lambda x: abs(x - (new_start + winLen)))
68 | new_start_idx = np.argwhere(time[:, 1] == new_start)[0, 0]
69 | new_end_idx = np.argwhere(time[:, 1] == new_end)[0, 0]
70 |
71 | sentences_sampled_user = sentences[new_start_idx:new_end_idx, :]
72 | time_sampled = time[new_start_idx:new_end_idx, :]
73 |
74 | hidden_batched_vector = sentences_sampled_user.cpu().data.numpy()
75 | hidden_batched_vector = hidden_batched_vector
76 | labels_tot = gauss.predict(hidden_batched_vector)
77 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
78 | freq = histog[0]
79 | frequency_vector[i, :] = freq / np.amax(freq)
80 | frequency_vector_mean = np.mean(frequency_vector, axis=0)
81 | users_pdf[idx, :] = frequency_vector_mean / np.sum(frequency_vector_mean)
82 |
83 | with open('../outputs/users_pdf.txt', "wb") as fp: # Pickling
84 | pickle.dump(users_pdf, fp)
85 |
86 | # COMPUTE THE USERS PDF ON THE TEST DATA
87 | winLen = 3000
88 | winStep = 30
89 | users_pdf = np.zeros((num_traces, num_clusters))
90 |
91 | for idx in range(num_traces):
92 | with open('../processed_files/hiddens_test_user' + str(idx) + '.txt',
93 | "rb") as fp: # Unpickling
94 | sentences = pickle.load(fp)
95 | with open('../processed_files/times_test_user' + str(idx) + '.txt',
96 | "rb") as fp: # Unpickling
97 | time = pickle.load(fp)
98 |
99 | time[:, 1] = time[:, 1] - time[0, 1]
100 | end = time[-1, 1]
101 | num_groups = int(mt.ceil((end - winLen) / winStep))
102 | frequency_vector = np.zeros((num_groups, num_clusters))
103 | for i in range(num_groups):
104 | new_start = min(list(time[:, 1]), key=lambda x: abs(x - i * winStep))
105 | new_end = min(list(time[:, 1]), key=lambda x: abs(x - (new_start + winLen)))
106 | new_start_idx = np.argwhere(time[:, 1] == new_start)[0, 0]
107 | new_end_idx = np.argwhere(time[:, 1] == new_end)[0, 0]
108 |
109 | sentences_sampled_user = sentences[new_start_idx:new_end_idx, :]
110 | time_sampled = time[new_start_idx:new_end_idx, :]
111 |
112 | hidden_batched_vector = sentences_sampled_user.cpu().data.numpy()
113 | hidden_batched_vector = hidden_batched_vector
114 | labels_tot = gauss.predict(hidden_batched_vector)
115 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
116 | freq = histog[0]
117 | frequency_vector[i, :] = freq / np.amax(freq)
118 | frequency_vector_mean = np.mean(frequency_vector, axis=0)
119 | users_pdf[idx, :] = frequency_vector_mean / np.sum(frequency_vector_mean)
120 |
121 | with open('../outputs/users_pdf_test.txt', "wb") as fp: # Pickling
122 | pickle.dump(users_pdf, fp)
123 |
124 | # COMPUTE THE DISTANCE METRICS FOR THE TRAIN DATA
125 | with open('../outputs/users_pdf.txt', "rb") as fp: # Unpickling
126 | users_pdf = pickle.load(fp)
127 |
128 | BC = np.zeros((num_traces, num_traces))
129 | for idx1 in range(num_traces):
130 | pdf_user1 = users_pdf[idx1, :]
131 | for idx2 in range(num_traces):
132 | if idx2 > idx1:
133 | pdf_user2 = users_pdf[idx2, :]
134 | BC[idx1, idx2] = -mt.log(np.sum(np.sqrt(np.multiply(pdf_user1, pdf_user2))))
135 |
136 | # COMPUTE THE DISTANCE METRICS FOR THE TEST DATA
137 | with open('../outputs/users_pdf_test.txt', "rb") as fp: # Unpickling
138 | users_pdf_test = pickle.load(fp)
139 |
140 | BC_test = np.zeros((num_traces, num_traces))
141 | for idx1 in range(num_traces):
142 | pdf_user1 = users_pdf_test[idx1, :]
143 | for idx2 in range(num_traces):
144 | if idx2 > idx1:
145 | pdf_user2 = users_pdf_test[idx2, :]
146 | BC_test[idx1, idx2] = -mt.log(np.sum(np.sqrt(np.multiply(pdf_user1, pdf_user2))))
147 |
148 | with open('../outputs/traces_test_accuracy.txt', "rb") as fp: # Unpickling
149 | traces_test_accuracy = pickle.load(fp)
150 |
151 | BC_test_line = BC_test.reshape(-1)
152 | traces_test_accuracy_line = traces_test_accuracy.reshape(-1)
153 |
154 | mApp_structure = sio.loadmat('../input_files/mApp.mat')
155 | mApp = mApp_structure['mApp']
156 |
157 | hamming_dist_app = np.zeros((num_traces, num_traces))
158 | matrix_app = np.zeros((num_traces, num_traces), dtype=int)
159 | for idx1 in range(num_traces):
160 | app_user1 = mApp[idx1, :]
161 | for idx2 in range(num_traces):
162 | app_user2 = mApp[idx2, :]
163 | if idx2 > idx1:
164 | dist_coeff = np.sum(np.abs(app_user1 - app_user2)) / (mt.pow(app_user1.shape[0], 2))
165 | hamming_dist_app[idx1, idx2] = dist_coeff
166 | matrix_app[idx1, idx2] = np.sum(app_user1 * app_user2) # app in common
167 |
168 | hamming_dist_app_line = hamming_dist_app.reshape(-1)
169 |
170 | fig = plt.figure(1)
171 | gs = gridspec.GridSpec(3, 3, wspace=0.38, hspace=0.68)
172 | ax1 = plt.subplot(gs[:, :-1])
173 | ax2 = plt.subplot(gs[0, -1:])
174 | ax3 = plt.subplot(gs[1, -1:])
175 | ax4 = plt.subplot(gs[2, -1:])
176 | ax1.scatter(hamming_dist_app_line / np.amax(hamming_dist_app_line), traces_test_accuracy_line, s=10, linewidths=0,
177 | c='firebrick', marker='x', label='Actual applications', linewidth=0.7)
178 | ax1.scatter(BC_test_line, traces_test_accuracy_line, s=10, linewidths=0, edgecolors='midnightblue', marker='o',
179 | label='Estimated applications', linewidth=0.4, facecolors='none')
180 | ax1.grid()
181 | ax1.tick_params(axis='both', which='major', labelsize=12)
182 | ax1.set_xlabel('Distance', FontSize=16)
183 | ax1.set_ylabel('Successful user disambiguation rate', FontSize=16)
184 | ax1.legend()
185 |
186 | idx = 3
187 | ax2.bar(np.linspace(1, num_clusters, num_clusters), users_pdf[idx, :], color='midnightblue')
188 | ax2.grid()
189 | ax2.set_title('User' + str(idx + 1), FontSize=16)
190 | ax2.set_xlabel('Clusters', FontSize=12)
191 | ax2.set_ylabel('Probability', FontSize=12)
192 | ax2.tick_params(axis='both', which='major', labelsize=12)
193 | ax2.set_xticks(np.linspace(1, num_clusters, num_clusters))
194 | ax2.locator_params(axis='x', nbins=5)
195 | ax2.locator_params(axis='y', nbins=5)
196 |
197 | idx = 4
198 | ax3.bar(np.linspace(1, num_clusters, num_clusters), users_pdf[idx, :], color='midnightblue')
199 | ax3.grid()
200 | ax3.set_title('User' + str(idx + 1), FontSize=16)
201 | ax3.set_xlabel('Clusters', FontSize=12)
202 | ax3.set_ylabel('Probability', FontSize=12)
203 | ax2.tick_params(axis='both', which='major', labelsize=12)
204 | ax3.set_xticks(np.linspace(1, num_clusters, num_clusters))
205 | ax3.locator_params(axis='x', nbins=5)
206 | ax3.locator_params(axis='y', nbins=5)
207 |
208 | idx = 11
209 | ax4.bar(np.linspace(1, num_clusters, num_clusters), users_pdf[idx, :], color='midnightblue')
210 | ax4.grid()
211 | ax4.set_title('User' + str(idx + 1), FontSize=16)
212 | ax4.set_xlabel('Clusters', FontSize=12)
213 | ax4.set_ylabel('Probability', FontSize=12)
214 | ax2.tick_params(axis='both', which='major', labelsize=12)
215 | ax4.set_xticks(np.linspace(1, num_clusters, num_clusters))
216 | ax4.locator_params(axis='x', nbins=5)
217 | ax4.locator_params(axis='y', nbins=5)
218 |
219 | fig.tight_layout()
220 | fig.set_size_inches(w=11, h=7)
221 | fig.savefig('../plots/batt_pdf.eps')
222 |
223 | # Confusion Matrix with numbers of common applications
224 | confusion_matrix = np.load('../outputs/confusion_matrix_test.npy')
225 |
226 | number_users = confusion_matrix.shape[0]
227 |
228 | confusion_matrix_normaliz_row = confusion_matrix / np.sum(confusion_matrix, axis=1).reshape(-1, 1)
229 | confusion_matrix_normaliz_column = \
230 | confusion_matrix_normaliz_row / np.sum(confusion_matrix_normaliz_row, axis=0).reshape(1, -1)
231 | max_columns = np.amax(confusion_matrix_normaliz_column, axis=0)
232 | sum_max_columns = np.sum(max_columns)
233 |
234 | correct_windows = np.sum(np.diag(confusion_matrix))
235 | number_windows = np.sum(np.sum(confusion_matrix, 1))
236 | perc_correct_window = correct_windows / number_windows * 100
237 | print('perc_correct_window: ' + str(perc_correct_window))
238 |
239 | fig = plt.figure(6)
240 | ax = plt.axes()
241 | fig.set_size_inches(6, 5)
242 | max_matrix_app = np.amax(confusion_matrix_normaliz_row)
243 | im1 = plt.pcolor(np.linspace(0.5, num_traces + 0.5, num_traces + 1),
244 | np.linspace(0.5, num_traces + 0.5, num_traces + 1),
245 | np.transpose(confusion_matrix_normaliz_row),
246 | cmap='Blues', edgecolors='black', vmin=0, vmax=max_matrix_app)
247 | ax.set_title(r"$\bf{" + "Normalized" + "}$" + " " r"$\bf{" + "confusion" + "}$" + " " r"$\bf{" + "matrix" + "}$",
248 | FontSize=9)
249 | ax.set_xlabel('Actual user', FontSize=8)
250 |
251 | ax.set_xticks(np.linspace(1, num_traces, num_traces), minor=True)
252 | ax.set_yticks(np.linspace(1, num_traces, num_traces), minor=True)
253 | ax.set_ylabel('Predicted user', FontSize=8)
254 | ax.tick_params(axis="x", labelsize=8)
255 | ax.tick_params(axis="y", labelsize=8)
256 |
257 | for y_ax in range(matrix_app.shape[0]):
258 | for x_ax in range(matrix_app.shape[1]):
259 | col = 'k'
260 | if confusion_matrix_normaliz_row[x_ax, y_ax] > 0.6: # [x, y] because plot the transpose version
261 | col = 'w'
262 | ax.text(x_ax + 1, y_ax + 1, '%d' % matrix_app[y_ax, x_ax], horizontalalignment='center',
263 | verticalalignment='center', fontsize=4, color=col)
264 |
265 | cbar = fig.colorbar(im1)
266 | cbar.ax.set_ylabel('Accuracy', FontSize=8)
267 | cbar.ax.tick_params(axis="y", labelsize=7)
268 |
269 | fig.savefig('../plots/users_apps.eps')
270 |
271 | with open('../outputs/matrix_app.txt', "wb") as fp: # Pickling
272 | pickle.dump(matrix_app, fp)
273 |
--------------------------------------------------------------------------------
/code/users_identification.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | users_identification: trains and validates the CNN for users identification
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib.pyplot as plt
25 | import tensorflow as tf
26 | from tensorflow.python.framework import ops
27 | import math as mt
28 | import pickle
29 | import gc
30 | plt.switch_backend('agg')
31 |
32 |
33 | def convert_to_one_hot(y, c):
34 | y = np.eye(c)[(y - 1).reshape(-1)].T
35 | return y
36 |
37 |
38 | def create_placeholders(max_length_sequences, n_y):
39 | x = tf.placeholder(tf.float32, shape=(None, max_length_sequences, 1))
40 | y = tf.placeholder(tf.float32, shape=(None, n_y))
41 | return x, y
42 |
43 |
44 | def initialize_parameters():
45 | tf.set_random_seed(1)
46 | w1 = tf.get_variable("W1", [10, 1, 5], initializer=tf.contrib.layers.xavier_initializer(seed=0))
47 | w2 = tf.get_variable("W2", [5, 5, 10], initializer=tf.contrib.layers.xavier_initializer(seed=0))
48 | w3 = tf.get_variable("W3", [5, 10, 20], initializer=tf.contrib.layers.xavier_initializer(seed=0))
49 | w4 = tf.get_variable("W4", [3, 20, 30], initializer=tf.contrib.layers.xavier_initializer(seed=0))
50 | parameters = {"w1": w1, "w2": w2, "w3": w3, "w4": w4}
51 | return parameters
52 |
53 |
54 | def cnn_encoder(x, parameters):
55 | w1 = parameters['w1']
56 | w2 = parameters['w2']
57 | w3 = parameters['w3']
58 | w4 = parameters['w4']
59 |
60 | z1 = tf.nn.conv1d(x, w1, stride=1, padding='SAME')
61 | a1 = tf.nn.relu(z1)
62 | d1 = tf.nn.dropout(a1, 0.8)
63 |
64 | z2 = tf.nn.conv1d(d1, w2, stride=1, padding='SAME')
65 | a2 = tf.nn.relu(z2)
66 | d2 = tf.nn.dropout(a2, 0.8)
67 |
68 | z3 = tf.nn.conv1d(d2, w3, stride=1, padding='SAME')
69 | a3 = tf.nn.relu(z3)
70 | d3 = tf.nn.dropout(a3, 0.8)
71 |
72 | z4 = tf.nn.conv1d(d3, w4, stride=1, padding='SAME')
73 | a4 = tf.nn.relu(z4)
74 |
75 | p6 = tf.contrib.layers.flatten(a4)
76 | p6 = tf.layers.dropout(p6, rate=0.2)
77 |
78 | z6 = tf.contrib.layers.fully_connected(p6, num_traces, activation_fn=None)
79 | return z6
80 |
81 |
82 | def compute_cost(z, y):
83 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=z, labels=y))
84 | return cost
85 |
86 |
87 | def confusion_matrix_computation(num_users, test_labels, prediction_test_labels):
88 | confusion_matrix = np.zeros((num_users, num_users))
89 | for i_act in range(1, num_users + 1): # actual user
90 | indices_act_i = np.argwhere(test_labels == i_act)[:, 0]
91 | for j_act in range(1, num_users + 1): # predicted user
92 | indices_act_j = np.argwhere(prediction_test_labels == j_act)[:, 0]
93 | intersect = set(indices_act_i).intersection(indices_act_j)
94 | confusion_matrix[i_act - 1, j_act - 1] = len(intersect)
95 | return confusion_matrix
96 |
97 |
98 | def random_mini_batches(x, y, mini_batch_size=64, seed=0):
99 | m = x.shape[0] # number of training examples
100 | mini_batches = []
101 | np.random.seed(seed)
102 |
103 | permutation = list(np.random.permutation(m))
104 | shuffled_x = x[permutation, :, :]
105 | shuffled_y = y[permutation, :]
106 |
107 | num_complete_minibatches = mt.floor(
108 | m / mini_batch_size) # number of mini batches of size mini_batch_size in your partitioning
109 | for k in range(0, num_complete_minibatches):
110 | mini_batch_x = shuffled_x[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :, :]
111 | mini_batch_y = shuffled_y[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :]
112 | mini_batch = (mini_batch_x, mini_batch_y)
113 | mini_batches.append(mini_batch)
114 |
115 | # Handling the end case (last mini-batch < mini_batch_size)
116 | if m % mini_batch_size != 0:
117 | mini_batch_x = shuffled_x[num_complete_minibatches * mini_batch_size: m, :, :]
118 | mini_batch_y = shuffled_y[num_complete_minibatches * mini_batch_size: m, :]
119 | mini_batch = (mini_batch_x, mini_batch_y)
120 | mini_batches.append(mini_batch)
121 |
122 | return mini_batches
123 |
124 |
125 | def model(x_train, y_train, x_test, y_test, test_accuracy_old, num_epochs=100, minibatch_size=64, print_cost=True):
126 | ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
127 | tf.set_random_seed(1)
128 | seed = 3
129 | (m, max_length_sequences, depth) = x_train.shape # m is the number of sequences
130 | (m_y, n_y) = y_train.shape
131 |
132 | costs = []
133 |
134 | x, y = create_placeholders(max_length_sequences, n_y)
135 |
136 | parameters = initialize_parameters()
137 |
138 | z6 = cnn_encoder(x, parameters)
139 |
140 | cost = compute_cost(z6, y)
141 |
142 | optimizer = tf.train.AdamOptimizer().minimize(cost)
143 |
144 | init = tf.global_variables_initializer()
145 |
146 | train_accuracy = 0
147 | test_accuracy = 0
148 |
149 | # Start the session to compute the tensorflow graph
150 | with tf.Session() as sess:
151 | sess.run(init)
152 |
153 | for epoch in range(num_epochs):
154 | minibatch_cost = 0.
155 | num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
156 | seed = seed + 1
157 | minibatches = random_mini_batches(x_train, y_train, minibatch_size, seed)
158 |
159 | for minibatch in minibatches:
160 | (minibatch_x, minibatch_y) = minibatch
161 |
162 | _, temp_cost = sess.run([optimizer, cost], feed_dict={x: minibatch_x, y: minibatch_y})
163 |
164 | minibatch_cost += temp_cost / num_minibatches
165 |
166 | # Print the cost
167 | if print_cost and epoch % 5 == 0:
168 | print("Cost after epoch %i: %f" % (epoch, minibatch_cost))
169 |
170 | predict_op = tf.argmax(z6, 1)
171 | correct_prediction = tf.equal(predict_op, tf.argmax(y, 1))
172 |
173 | # Calculate accuracy on the test set
174 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
175 |
176 | train_accuracy = accuracy.eval({x: x_train, y: y_train})
177 |
178 | test_accuracy = accuracy.eval({x: x_test, y: y_test})
179 |
180 | print("Train accuracy: %f" % train_accuracy)
181 | print("Test accuracy:%f " % test_accuracy)
182 |
183 | if print_cost and epoch % 10 == 0:
184 | costs.append(minibatch_cost)
185 |
186 | # Save the prediction
187 | prediction_train = sess.run(z6, {x: x_train, y: y_train})
188 | prediction_test = sess.run(z6, {x: x_test, y: y_test})
189 |
190 | prediction_train_label = np.argmax(prediction_train, axis=1) + 1
191 | prediction_test_label = np.argmax(prediction_test, axis=1) + 1
192 |
193 | if test_accuracy > test_accuracy_old:
194 | confusion_matrix_test = confusion_matrix_computation(num_traces, test_label, prediction_test_label)
195 | confusion_matrix_train = confusion_matrix_computation(num_traces, train_label, prediction_train_label)
196 | test_accuracy_old = test_accuracy
197 |
198 | gc.collect()
199 | np.save("../outputs/confusion_matrix_test.npy", confusion_matrix_test)
200 | np.save("../outputs/confusion_matrix_train.npy", confusion_matrix_train)
201 |
202 | sess.close()
203 |
204 | return train_accuracy, test_accuracy, parameters, prediction_train, prediction_test
205 |
206 |
207 | if __name__ == '__main__':
208 | parser = argparse.ArgumentParser(description=__doc__)
209 | parser.add_argument('num_clusters', help='Number of classes for clustering', type=int)
210 | parser.add_argument('epochs', help='Number of epochs', type=int)
211 | args = parser.parse_args()
212 |
213 | num_traces = 40
214 |
215 | # ---------------------------------------------------------------------------------------------------------------- #
216 | # CONVOLUTIONAL NETWORK USER IDENTIFICATION #
217 |
218 | num_clusters = args.num_clusters
219 | with open('../processed_files/gauss.txt', "rb") as fp: # Unpickling
220 | gauss = pickle.load(fp)
221 |
222 | num_epcs = args.epochs
223 | len_win = 3000 # in seconds
224 | step_win = 30 # in seconds
225 | users_sliding = []
226 | index_vector = []
227 | user_new = 0
228 | for user in range(num_traces):
229 | print(user)
230 | with open('../processed_files/hiddens_' + 'train' + '_user' + str(user) + '.txt',
231 | "rb") as fp: # Unpickling
232 | sentences_u = pickle.load(fp)
233 | with open('../processed_files/times_' + 'train' + '_user' + str(user) + '.txt',
234 | "rb") as fp: # Unpickling
235 | time_u = pickle.load(fp)
236 | sentences_u = sentences_u.data.cpu().numpy()
237 | time_ass = time_u[:, 1] - time_u[0, 1]
238 | length_user = time_ass[-1]
239 | sentences_k = []
240 | num_window = mt.ceil((length_user-len_win)/step_win)
241 |
242 | print('user ' + str(user) + ': train window ' + str(num_window))
243 | for t in range(num_window):
244 | indices = np.argwhere((time_ass > t*step_win) & (time_ass < t*step_win + len_win))[:, 0]
245 | if indices.shape[0] > 1:
246 | sentences_k.append(sentences_u[indices[0]:indices[-1], :])
247 |
248 | frequency_vector = np.zeros((len(sentences_k), num_clusters))
249 | for s in range(len(sentences_k)):
250 | sentence = np.asarray(sentences_k[s])
251 | hidden_batched_vector = sentence
252 | labels_tot = gauss.predict(hidden_batched_vector)
253 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
254 | freq = histog[0]
255 | frequency_vector[s, :] = freq/np.amax(freq)
256 |
257 | users_sliding.append(frequency_vector)
258 | index_vector.extend(len(sentences_k) * [user_new])
259 | user_new = user_new + 1
260 |
261 | input_matrix_tr = np.vstack(users_sliding)
262 | train_label = np.asarray(index_vector) + 1
263 |
264 | users_sliding = []
265 | index_vector = []
266 | len_win = 3000 # in seconds
267 | step_win = 30 # in seconds
268 | user_new = 0
269 | for user in range(num_traces):
270 | print(user)
271 | with open('../processed_files/hiddens_test_user' + str(user) + '.txt',
272 | "rb") as fp: # Unpickling
273 | sentences_u = pickle.load(fp)
274 | with open('../processed_files/times_test_user' + str(user) + '.txt',
275 | "rb") as fp: # Unpickling
276 | time_u = pickle.load(fp)
277 | sentences_u = sentences_u.data.cpu().numpy()
278 | time_ass = time_u[:, 1] - time_u[0, 1]
279 | length_user = time_ass[-1]
280 | sentences_k = []
281 | num_window = mt.ceil((length_user-len_win)/step_win)
282 | print('user ' + str(user) + ': test window ' + str(num_window))
283 | for t in range(num_window):
284 | indices = np.argwhere((time_ass > t*step_win) & (time_ass < t*step_win + len_win))[:, 0]
285 | if indices.shape[0] > 1:
286 | sentences_k.append(sentences_u[indices[0]:indices[-1], :])
287 |
288 | frequency_vector = np.zeros((len(sentences_k), num_clusters))
289 | for s in range(len(sentences_k)):
290 | sentence = np.asarray(sentences_k[s])
291 | hidden_batched_vector = sentence
292 | labels_tot = gauss.predict(hidden_batched_vector)
293 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
294 | freq = histog[0]
295 | frequency_vector[s, :] = freq/np.amax(freq)
296 |
297 | users_sliding.append(frequency_vector)
298 | index_vector.extend(len(sentences_k) * [user_new])
299 | user_new = user_new + 1
300 |
301 | input_matrix_test = np.vstack(users_sliding)
302 | test_label = np.asarray(index_vector) + 1
303 |
304 | input_matrix_tr = input_matrix_tr.reshape((input_matrix_tr.shape[0], input_matrix_tr.shape[1], 1))
305 | input_matrix_test = input_matrix_test.reshape((input_matrix_test.shape[0], input_matrix_test.shape[1], 1))
306 |
307 | output_matrix_tr = convert_to_one_hot(train_label, num_traces).T
308 | output_matrix_test = convert_to_one_hot(test_label, num_traces).T
309 |
310 | test_accuracy_input = 0
311 | _, test_accuracy_new, parameters_out, prediction_tr, prediction_tst = model(input_matrix_tr, output_matrix_tr,
312 | input_matrix_test, output_matrix_test,
313 | test_accuracy_input,
314 | num_epochs=num_epcs)
315 |
--------------------------------------------------------------------------------
/code/users_disambiguation.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | users_disambiguation: computes the accuracy in the separation between two users
4 |
5 | Copyright (C) 2019 Francesca Meneghello, Michele Rossi, Nicola Bui
6 | contact: meneghello@dei.unipd.it
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 | """
21 |
22 | import argparse
23 | import numpy as np
24 | import matplotlib.pyplot as plt
25 | import tensorflow as tf
26 | from tensorflow.python.framework import ops
27 | import math as mt
28 | import pickle
29 | import gc
30 | from pathlib import Path
31 | plt.switch_backend('agg')
32 |
33 |
34 | def convert_to_one_hot(y, c):
35 | y = np.eye(c)[(y - 1).reshape(-1)].T
36 | return y
37 |
38 |
39 | def create_placeholders(max_length_sequences, n_y):
40 | x = tf.placeholder(tf.float32, shape=(None, max_length_sequences, 1))
41 | y = tf.placeholder(tf.float32, shape=(None, n_y))
42 | return x, y
43 |
44 |
45 | def initialize_parameters():
46 | tf.set_random_seed(1)
47 | w1 = tf.get_variable("W1", [10, 1, 5], initializer=tf.contrib.layers.xavier_initializer(seed=0))
48 | w2 = tf.get_variable("W2", [5, 5, 10], initializer=tf.contrib.layers.xavier_initializer(seed=0))
49 | w3 = tf.get_variable("W3", [5, 10, 20], initializer=tf.contrib.layers.xavier_initializer(seed=0))
50 | w4 = tf.get_variable("W4", [3, 20, 30], initializer=tf.contrib.layers.xavier_initializer(seed=0))
51 | parameters = {"w1": w1, "w2": w2, "w3": w3, "w4": w4}
52 | return parameters
53 |
54 |
55 | def cnn_encoder(x, parameters):
56 | w1 = parameters['w1']
57 | w2 = parameters['w2']
58 | w3 = parameters['w3']
59 | w4 = parameters['w4']
60 |
61 | z1 = tf.nn.conv1d(x, w1, stride=1, padding='SAME')
62 | a1 = tf.nn.relu(z1)
63 | d1 = tf.nn.dropout(a1, 0.8)
64 |
65 | z2 = tf.nn.conv1d(d1, w2, stride=1, padding='SAME')
66 | a2 = tf.nn.relu(z2)
67 | d2 = tf.nn.dropout(a2, 0.8)
68 |
69 | z3 = tf.nn.conv1d(d2, w3, stride=1, padding='SAME')
70 | a3 = tf.nn.relu(z3)
71 | d3 = tf.nn.dropout(a3, 0.8)
72 |
73 | z4 = tf.nn.conv1d(d3, w4, stride=1, padding='SAME')
74 | a4 = tf.nn.relu(z4)
75 |
76 | p6 = tf.contrib.layers.flatten(a4)
77 | p6 = tf.layers.dropout(p6, rate=0.2)
78 |
79 | z6 = tf.contrib.layers.fully_connected(p6, num_selected_traces, activation_fn=None)
80 | return z6
81 |
82 |
83 | def compute_cost(z, y):
84 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=z, labels=y))
85 | return cost
86 |
87 |
88 | def confusion_matrix_computation(num_users, test_labels, prediction_test_labels):
89 | confusion_matrix = np.zeros((num_users, num_users))
90 | for i_act in range(1, num_users + 1): # actual user
91 | indices_act_i = np.argwhere(test_labels == i_act)[:, 0]
92 | for j_act in range(1, num_users + 1): # predicted user
93 | indices_act_j = np.argwhere(prediction_test_labels == j_act)[:, 0]
94 | intersect = set(indices_act_i).intersection(indices_act_j)
95 | confusion_matrix[i_act - 1, j_act - 1] = len(intersect)
96 | return confusion_matrix
97 |
98 |
99 | def random_mini_batches(x, y, mini_batch_size=64, seed=0):
100 | m = x.shape[0] # number of training examples
101 | mini_batches = []
102 | np.random.seed(seed)
103 |
104 | permutation = list(np.random.permutation(m))
105 | shuffled_x = x[permutation, :, :]
106 | shuffled_y = y[permutation, :]
107 |
108 | num_complete_minibatches = mt.floor(
109 | m / mini_batch_size) # number of mini batches of size mini_batch_size in your partitioning
110 | for k in range(0, num_complete_minibatches):
111 | mini_batch_x = shuffled_x[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :, :]
112 | mini_batch_y = shuffled_y[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :]
113 | mini_batch = (mini_batch_x, mini_batch_y)
114 | mini_batches.append(mini_batch)
115 |
116 | # Handling the end case (last mini-batch < mini_batch_size)
117 | if m % mini_batch_size != 0:
118 | mini_batch_x = shuffled_x[num_complete_minibatches * mini_batch_size: m, :, :]
119 | mini_batch_y = shuffled_y[num_complete_minibatches * mini_batch_size: m, :]
120 | mini_batch = (mini_batch_x, mini_batch_y)
121 | mini_batches.append(mini_batch)
122 |
123 | return mini_batches
124 |
125 |
126 | def model(x_train, y_train, x_test, y_test, test_accuracy_old, num_epochs=100, minibatch_size=64, print_cost=True):
127 | ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
128 | tf.set_random_seed(1)
129 | seed = 3
130 | (m, max_length_sequences, depth) = x_train.shape # m is the number of sequences
131 | (m_y, n_y) = y_train.shape
132 |
133 | costs = []
134 |
135 | x, y = create_placeholders(max_length_sequences, n_y)
136 |
137 | parameters = initialize_parameters()
138 |
139 | z6 = cnn_encoder(x, parameters)
140 |
141 | cost = compute_cost(z6, y)
142 |
143 | optimizer = tf.train.AdamOptimizer().minimize(cost)
144 |
145 | init = tf.global_variables_initializer()
146 |
147 | train_accuracy = 0
148 | test_accuracy = 0
149 |
150 | # Start the session to compute the tensorflow graph
151 | with tf.Session() as sess:
152 | sess.run(init)
153 |
154 | for epoch in range(num_epochs):
155 | minibatch_cost = 0.
156 | num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
157 | seed = seed + 1
158 | minibatches = random_mini_batches(x_train, y_train, minibatch_size, seed)
159 |
160 | for minibatch in minibatches:
161 | (minibatch_x, minibatch_y) = minibatch
162 |
163 | _, temp_cost = sess.run([optimizer, cost], feed_dict={x: minibatch_x, y: minibatch_y})
164 |
165 | minibatch_cost += temp_cost / num_minibatches
166 |
167 | # Print the cost
168 | if print_cost and epoch % 5 == 0:
169 | print("Cost after epoch %i: %f" % (epoch, minibatch_cost))
170 |
171 | predict_op = tf.argmax(z6, 1)
172 | correct_prediction = tf.equal(predict_op, tf.argmax(y, 1))
173 |
174 | # Calculate accuracy on the test set
175 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
176 |
177 | train_accuracy = accuracy.eval({x: x_train, y: y_train})
178 |
179 | test_accuracy = accuracy.eval({x: x_test, y: y_test})
180 |
181 | print("Train accuracy: %f" % train_accuracy)
182 | print("Test accuracy:%f " % test_accuracy)
183 |
184 | if print_cost and epoch % 10 == 0:
185 | costs.append(minibatch_cost)
186 |
187 | # Save the prediction
188 | prediction_train = sess.run(z6, {x: x_train, y: y_train})
189 | prediction_test = sess.run(z6, {x: x_test, y: y_test})
190 |
191 | if test_accuracy > test_accuracy_old:
192 | test_accuracy_old = test_accuracy
193 |
194 | gc.collect()
195 |
196 | sess.close()
197 |
198 | return train_accuracy, test_accuracy, parameters, prediction_train, prediction_test
199 |
200 |
201 | if __name__ == '__main__':
202 | parser = argparse.ArgumentParser(description=__doc__)
203 | parser.add_argument('num_clusters', help='Number of classes for clustering', type=int)
204 | parser.add_argument('epochs', help='Number of epochs', type=int)
205 | args = parser.parse_args()
206 |
207 | num_traces = 40
208 |
209 | # ---------------------------------------------------------------------------------------------------------------- #
210 | # CONVOLUTIONAL NETWORK USER IDENTIFICATION #
211 |
212 | num_clusters = args.num_clusters
213 | with open('../processed_files/gauss.txt', "rb") as fp: # Unpickling
214 | gauss = pickle.load(fp)
215 |
216 | num_selected_traces = 2
217 |
218 | num_epcs = args.epochs
219 |
220 | my_file = Path('../outputs/traces_test_accuracy.txt')
221 | if my_file.is_file():
222 | with open('../outputs/traces_test_accuracy.txt', "rb") as fp: # Unpickling
223 | traces_test_accuracy = pickle.load(fp)
224 | start_idx1 = np.argwhere(np.diag(traces_test_accuracy, 1) == 0)[0, 0] - 1
225 | start_idx2 = np.argwhere(traces_test_accuracy[start_idx1, start_idx1 + 1:] == 0)
226 | if len(start_idx2) == 0:
227 | start_idx1 = start_idx1 + 1
228 | start_idx2 = start_idx1 + 1
229 | else:
230 | start_idx2 = start_idx2[0, 0] + start_idx1 + 1
231 | else:
232 | traces_test_accuracy = np.zeros((num_traces, num_traces))
233 | start_idx1 = 0
234 | start_idx2 = 1
235 |
236 | for idx1 in range(start_idx1, num_traces):
237 | if start_idx1 != idx1:
238 | start_idx2 = idx1 + 1
239 | for idx2 in range(start_idx2, num_traces):
240 | print(' ')
241 | print('idx1 ' + str(idx1))
242 | print('idx2 ' + str(idx2))
243 | selected_indices = np.asarray([idx1, idx2])
244 |
245 | len_win = 3000 # in seconds
246 | step_win = 30 # in seconds
247 | users_sliding = []
248 | index_vector = []
249 | user_new = 0
250 | for user in selected_indices:
251 | print(user)
252 | with open('../processed_files/hiddens_train_user' + str(user) + '.txt',
253 | "rb") as fp: # Unpickling
254 | sentences_u = pickle.load(fp)
255 | with open('../processed_files/times_train_user' + str(user) + '.txt',
256 | "rb") as fp: # Unpickling
257 | time_u = pickle.load(fp)
258 | sentences_u = sentences_u.data.cpu().numpy()
259 | time_ass = time_u[:, 1] - time_u[0, 1]
260 | length_user = time_ass[-1]
261 | sentences_k = []
262 | num_window = mt.ceil((length_user - len_win) / step_win)
263 |
264 | print('user ' + str(user) + ': train window ' + str(num_window))
265 | for t in range(num_window):
266 | indices = np.argwhere((time_ass > t * step_win) & (time_ass < t * step_win + len_win))[:, 0]
267 | if indices.shape[0] > 1:
268 | sentences_k.append(sentences_u[indices[0]:indices[-1], :])
269 |
270 | frequency_vector = np.zeros((len(sentences_k), num_clusters))
271 | for s in range(len(sentences_k)):
272 | sentence = np.asarray(sentences_k[s])
273 | hidden_batched_vector = sentence
274 | labels_tot = gauss.predict(hidden_batched_vector)
275 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
276 | freq = histog[0]
277 | frequency_vector[s, :] = freq / np.amax(freq)
278 |
279 | users_sliding.append(frequency_vector)
280 | index_vector.extend(len(sentences_k) * [user_new])
281 | user_new = user_new + 1
282 |
283 | input_matrix_tr = np.vstack(users_sliding)
284 | train_label = np.asarray(index_vector) + 1
285 |
286 | users_sliding = []
287 | index_vector = []
288 | len_win = 3000 # in seconds
289 | step_win = 30 # in seconds
290 | user_new = 0
291 | for user in selected_indices:
292 | print(user)
293 | with open('../processed_files/hiddens_test_user' + str(user) + '.txt',
294 | "rb") as fp: # Unpickling
295 | sentences_u = pickle.load(fp)
296 | with open('../processed_files/times_test_user' + str(user) + '.txt',
297 | "rb") as fp: # Unpickling
298 | time_u = pickle.load(fp)
299 | sentences_u = sentences_u.data.cpu().numpy()
300 | time_ass = time_u[:, 1] - time_u[0, 1]
301 | length_user = time_ass[-1]
302 | sentences_k = []
303 | num_window = mt.ceil((length_user - len_win) / step_win)
304 |
305 | print('user ' + str(user) + ': test window ' + str(num_window))
306 | for t in range(num_window):
307 | indices = np.argwhere((time_ass > t * step_win) & (time_ass < t * step_win + len_win))[:, 0]
308 | if indices.shape[0] > 1:
309 | sentences_k.append(sentences_u[indices[0]:indices[-1], :])
310 |
311 | frequency_vector = np.zeros((len(sentences_k), num_clusters))
312 | for s in range(len(sentences_k)):
313 | sentence = np.asarray(sentences_k[s])
314 | hidden_batched_vector = sentence
315 | labels_tot = gauss.predict(hidden_batched_vector)
316 | histog = np.histogram(labels_tot, bins=np.linspace(0, num_clusters, num_clusters + 1))
317 | freq = histog[0]
318 | frequency_vector[s, :] = freq/np.amax(freq)
319 |
320 | users_sliding.append(frequency_vector)
321 | index_vector.extend(len(sentences_k) * [user_new])
322 | user_new = user_new + 1
323 |
324 | input_matrix_test = np.vstack(users_sliding)
325 | test_label = np.asarray(index_vector) + 1
326 |
327 | input_matrix_tr = input_matrix_tr.reshape((input_matrix_tr.shape[0], input_matrix_tr.shape[1], 1))
328 | input_matrix_test = input_matrix_test.reshape((input_matrix_test.shape[0], input_matrix_test.shape[1], 1))
329 |
330 | output_matrix_tr = convert_to_one_hot(train_label, num_selected_traces).T
331 | output_matrix_test = convert_to_one_hot(test_label, num_selected_traces).T
332 |
333 | test_acc_old = 0
334 | _, test_accuracy_new, _, _, _ = model(input_matrix_tr, output_matrix_tr, input_matrix_test,
335 | output_matrix_test, test_acc_old, num_epochs=num_epcs)
336 |
337 | traces_test_accuracy[idx1, idx2] = test_accuracy_new
338 |
339 | with open('../processed_files/traces_test_accuracy.txt', "wb") as fp: # Pickling
340 | pickle.dump(traces_test_accuracy, fp)
341 | del input_matrix_tr
342 | del input_matrix_test
343 | del output_matrix_test
344 | del output_matrix_tr
345 | del test_label
346 | gc.collect()
347 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------