Canva,澳洲独角兽,base悉尼, 在招聘Senior MLE,我投了他家的NLU相关的职位,三月中下旬投的然后,四月初约的第一轮phone screen,4月23号月的VO。VO 一共四轮,两轮coding,一轮system design,一轮behavior。 所有的coding题目都不是Leetcode,而是做一些ML的implementation
phone screen: 原题
coding 1:
给了一个logistic regression的代码,给出的场景是在production环境下model表现不好,问可能有哪些原因。
答:要么是data的问题,train prod data distribution不一样,要么是模型overfitting。
然后面试官说如果overfitting怎么处理,
我说可以考虑train dev test split,在每次epoch后再dev上验证是否overfitting, 也可以考虑加penalty防止weights dominate loss。然后面试官说好第一问是如何在现有的logisitic regression的代码上实现L2 regularization,做完后说如果我们想实现不同的regularization该怎么改动。- import dataclasses
- import logging
- import numpy as np
- logging.basicConfig(level=logging.INFO)
- logger = logging.getLogger()
- logger = logging.getLogger()
- FEATURE_TYPE = np.float64
- RESPONSE_TYPE = np.int8
- from abc import ABC
- from abc import abstractmethod
- class Regularizer(ABC):
- @abstractmethod
- def gradiate_penalty(self, coefficients: np.array) -> np.array:
- pass
- @abstractmethod
- def loss_penalty(self, coefficients: np.array) -> np.array:
- pass
- class L2Regularizer(Regularizer):
- def __init__(self, lambda_param):
- self.lambda_param = lambda_param
- def gradiate_penalty(self, coefficients):
- return 2*self.lambda_param*coefficients
- def loss_penalty(self, coefficients: np.array) -> np.array:
- return self.lambda_param * np.sum(coefficients ** 2)
- @dataclasses.dataclass
- class Hyperparameters:
- """Encapsulates the training hyperparameters."""
- epochs: int = 8
- learning_rate: float = 0.01
- batch_size: int = 32
- seed: int = 42
- regularizer: Regularizer = L2Regularizer(0.1)
- @dataclasses.dataclass
- class Dataset:
- """Stores features and their accompanying responses."""
- features: np.ndarray
- responses: np.ndarray
- def __post_init__(self):
- assert self.features.shape[0] == self.responses.shape[0]
- class LogisticRegressionModel:
- """Predicts responses for a Dataset."""
- def __init__(
- self,
- coefficients: np.ndarray,
- ):
- if coefficients.ndim != 1:
- raise ValueError(f"Unexpected coefficient ndim (found {coefficients.ndim})")
- self.coefficients = coefficients
- def compute_probabilities(self, features: np.ndarray) -> np.ndarray:
- return _compute_probabilities(features, self.coefficients)
- def predict(self, dataset: Dataset, threshold: float = 0.5) -> np.ndarray:
- probabilities = self.compute_probabilities(dataset.features)
- return (probabilities > threshold).astype(np.int8)
- class LogisticRegressionFitter:
- """Fits a Logistic Regression model using minibatch stochastic gradient descent."""
- def __init__(
- self,
- hyperparameters: Hyperparameters,
- ):
- self.hyperparameters = hyperparameters
- self.epoch_losses: list[float] = []
- def fit(self, dataset: Dataset) -> LogisticRegressionModel:
- """Returns a LogisticRegressionModel by fitting the supplied dataset"""
- assert dataset.features.ndim == 2
- num_instances, num_features = dataset.features.shape
- coefficients = np.zeros(num_features)
- for epoch in range(self.hyperparameters.epochs):
- # Visit the feature rows in random order.
- row_indices = np.argsort(
- np.random.uniform(low=0, high=1, size=num_instances), axis=0
- )
- # Mini-batches over the shuffled dataset.
- shuffled_features = dataset.features[row_indices]
- shuffled_responses = dataset.responses[row_indices]
- for batch_index in range(
- int(num_instances / self.hyperparameters.batch_size)
- ):
- batch_start = batch_index * self.hyperparameters.batch_size
- batch_end = batch_start + self.hyperparameters.batch_size
- batch_features = shuffled_features[batch_start:batch_end]
- batch_responses = shuffled_responses[batch_start:batch_end].reshape(
- (self.hyperparameters.batch_size, 1)
- )
- batch_predictions = _compute_probabilities(
- batch_features, coefficients
- ).reshape((self.hyperparameters.batch_size, 1))
- gradient = _compute_cross_entropy_loss_gradient(
- batch_features,
- batch_responses,
- batch_predictions,
- ) + self.hyperparameters.regularizer.gradiate_penalty(coefficients)
- coefficients -= self.hyperparameters.learning_rate * gradient
- # Evaluate epoch loss.
- y = dataset.responses.astype(RESPONSE_TYPE)
- y_hat = _compute_probabilities(dataset.features, coefficients)
- epoch_loss = _compute_cross_entropy_loss(y, y_hat) + self.hyperparameters.regularizer.loss_penalty(coefficients)
- self.epoch_losses.append(epoch_loss)
- logger.info(f"[{epoch}]\tLoss {epoch_loss:.7f}")
- return LogisticRegressionModel(coefficients=coefficients)
- def _compute_probabilities(features: np.array, coefficients: np.array) -> np.array:
- return _sigmoid(np.matmul(features, coefficients))
- def _sigmoid(z: np.array) -> np.array:
- return 1 / (1 + np.exp(-z))
- def _compute_cross_entropy_loss(y: np.array, y_hat: np.array) -> np.array:
- return np.mean(-y * np.log(y_hat) - (1 - y) * np.log(1 - y_hat))
- def _compute_cross_entropy_loss_gradient(
- x: np.array, y: np.array, y_hat: np.array
- ) -> np.array:
- residuals = (y_hat - y).reshape((-1, 1))
- return (x * residuals).mean(axis=0)
- def main():
- hyperparameters = Hyperparameters()
- np.random.seed(hyperparameters.seed)
- num_features = 5
- dataset_generator = DatasetGenerator(num_features=num_features)
- dataset = dataset_generator.generate(num_samples=hyperparameters.batch_size * 10)
- fitter = LogisticRegressionFitter(hyperparameters=hyperparameters)
- model = fitter.fit(dataset)
- logger.info(
- f"[🏁]\tCoefficients: {[round(c, 2) for c in model.coefficients.tolist()]}\tNorm: {np.linalg.norm(model.coefficients):.2f}"
- )
- num_heldout_samples = 100
- heldout_dataset = dataset_generator.generate(num_samples=num_heldout_samples)
- heldout_predictions = model.predict(heldout_dataset)
- heldout_accuracy = calculate_accuracy(
- responses=heldout_dataset.responses, predictions=heldout_predictions
- )
- logger.info(f"[🏁]\tHeldout accuracy: {heldout_accuracy}")
- # Checks.
- if monotonically_decreases_or_stabilizes(fitter.epoch_losses):
- logger.info("[✅]\tEpoch losses decrease and stabilize during training.")
- else:
- logger.info("[❌]\tEpoch losses do not decrease or stablize during training.")
- if heldout_accuracy > 0.9:
- logger.info("[✅]\tAccuracy on heldout dataset is high enough.")
- else:
- logger.info("[❌]\tAccuracy on heldout dataset is not high enough.")
- # STOP READING HERE.
- # NO NEED TO READ BELOW HERE.
- class DatasetGenerator:
- """
- Creates sample datasets, inspired by sklearn's make_blobs.
- """
- def __init__(self, num_features: int = 10):
- self.num_features = num_features
- self.num_centers = 2
- center_box = (-10.0, 10.0)
- self.centers = np.random.uniform(
- center_box[0], center_box[1], size=(self.num_centers, num_features)
- )
- self.cluster_std = np.full(len(self.centers), 1.0)
- def generate(self, num_samples: int) -> Dataset:
- X = []
- y = []
- num_samples_per_center = [
- int(num_samples // self.num_centers)
- ] * self.num_centers
- for i in range(num_samples % self.num_centers):
- num_samples_per_center[i] += 1
- for i, (n, std) in enumerate(zip(num_samples_per_center, self.cluster_std)):
- X.append(
- np.random.normal(
- loc=self.centers[i], scale=std, size=(n, self.num_features)
- )
- )
- y += [i] * n
- X = np.concatenate(X)
- y = np.array(y)
- total_num_samples = np.sum(num_samples)
- indices = np.arange(total_num_samples)
- np.random.shuffle(indices)
- return Dataset(
- features=X[indices].astype(FEATURE_TYPE),
- responses=y[indices].astype(RESPONSE_TYPE),
- )
- def calculate_accuracy(responses: np.ndarray, predictions: np.ndarray) -> float:
- return np.sum(responses == predictions) / predictions.shape[0]
- def monotonically_decreases_or_stabilizes(values: list[float]) -> bool:
- return all(i >= j for i, j in zip(values[:-1], values[1:]))
- if __name__ == "__main__":
- main()
复制代码 这是第一问的代码。
第二轮 coding:
给了一个图形处理的场景。
第一问实现一个image的sanitize_imaroject scope,怎么样deal with conflicts,你有没有过behavior change to accomplish sth之类的。
今天收到HR feedback说Overall you did well, however, the interviewers agreed on a mid-level performance which unfortunately doesn't match any of the open roles currently.
身在国内,被外企雷已经四个月了,还没有上岸,想着试试澳大利亚的机会还是没有抓住,面经分享给地里的人希望能帮助到需要的人也帮自己攒个人品了。求大米 |