|
| 1 | +import torch |
| 2 | +from sklearn.metrics import accuracy_score |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +class SquareLoss: |
| 6 | + def __init__(self): |
| 7 | + pass |
| 8 | + |
| 9 | + def loss(self, y, y_pred): |
| 10 | + return 0.5 * torch.pow((y - y_pred), 2) |
| 11 | + |
| 12 | + def gradient(self, y, y_pred): |
| 13 | + return -(y - y_pred) |
| 14 | + |
| 15 | +class CrossEntropy: |
| 16 | + def __init__(self): |
| 17 | + pass |
| 18 | + |
| 19 | + def loss(self, y, p): |
| 20 | + p = torch.clip(p, 1e-15, 1 - 1e-15) |
| 21 | + return - y * torch.log(p) - (1 - y) * torch.log(1 - p) |
| 22 | + |
| 23 | + def accuracy(self, y, p): |
| 24 | + return accuracy_score(torch.argmax(y, dim=1), torch.argmax(p, dim=1)) |
| 25 | + |
| 26 | + def gradient(self, y, p): |
| 27 | + p = torch.clip(p, 1e-15, 1 - 1e-15) |
| 28 | + return -(y/p) + (1-y) / (1-p) |
| 29 | + |
| 30 | +def euclidean_distance(x1, x2): |
| 31 | + """ |
| 32 | + :param x1: input tensor |
| 33 | + :param x2: input tensor |
| 34 | + :return: distance between tensors |
| 35 | + """ |
| 36 | + |
| 37 | + return torch.cdist(x1.unsqueeze(0), x2.unsqueeze(0)) |
| 38 | + |
| 39 | +def to_categorical(X, n_columns=None): |
| 40 | + if not n_columns: |
| 41 | + n_columns = torch.amax(X) + 1 |
| 42 | + one_hot = torch.zeros((X.shape[0], n_columns)) |
| 43 | + one_hot[torch.arange(X.shape[0])] = 1 |
| 44 | + return one_hot |
| 45 | + |
| 46 | +def mean_squared_error(y_true, y_pred): |
| 47 | + mse = torch.mean(torch.pow(y_true - y_pred, 2)) |
| 48 | + return mse |
| 49 | + |
| 50 | +def divide_on_feature(X, feature_i, threshold): |
| 51 | + |
| 52 | + split_func = None |
| 53 | + if isinstance(threshold, int) or isinstance(threshold, float): |
| 54 | + split_func = lambda sample: sample[feature_i] >= threshold |
| 55 | + else: |
| 56 | + split_func = lambda sample: sample[feature_i] == threshold |
| 57 | + |
| 58 | + |
| 59 | + X_1 = torch.tensor([sample.numpy() for sample in X if split_func(sample)]) |
| 60 | + X_2 = torch.tensor([sample.numpy() for sample in X if not split_func(sample)]) |
| 61 | + |
| 62 | + return np.array([X_1.numpy(), X_2.numpy()], dtype='object') |
| 63 | + |
| 64 | +def calculate_variance(X): |
| 65 | + mean = torch.ones(X.shape) * torch.mean(X, dim=0) |
| 66 | + n_samples = X.shape[0] |
| 67 | + variance = (1/ n_samples) * torch.diag(torch.mm((X-mean).T, (X-mean))) |
| 68 | + return variance |
0 commit comments