📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

Canva Senior MLE VO Sydney 挂经

全局:

2024(4-6月) 码农类General 硕士 全职@canva - 网上海投 - 技术电面  | 😃 Positive 😐 Average | Other | 其他
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该怎么改动。
  1. import dataclasses
  2. import logging

  3. import numpy as np

  4. logging.basicConfig(level=logging.INFO)
  5. logger = logging.getLogger()
  6. logger = logging.getLogger()

  7. FEATURE_TYPE = np.float64
  8. RESPONSE_TYPE = np.int8

  9. from abc import ABC
  10. from abc import abstractmethod

  11. class Regularizer(ABC):

  12.     @abstractmethod
  13.     def gradiate_penalty(self, coefficients: np.array) -> np.array:
  14.         pass

  15.     @abstractmethod
  16.     def loss_penalty(self, coefficients: np.array) -> np.array:
  17.         pass

  18. class L2Regularizer(Regularizer):
  19.     def __init__(self, lambda_param):
  20.         self.lambda_param = lambda_param

  21.     def gradiate_penalty(self, coefficients):
  22.         return 2*self.lambda_param*coefficients

  23.     def loss_penalty(self, coefficients: np.array) -> np.array:
  24.         return  self.lambda_param * np.sum(coefficients ** 2)


  25. @dataclasses.dataclass
  26. class Hyperparameters:
  27.     """Encapsulates the training hyperparameters."""

  28.     epochs: int = 8
  29.     learning_rate: float = 0.01
  30.     batch_size: int = 32
  31.     seed: int = 42
  32.     regularizer: Regularizer = L2Regularizer(0.1)


  33. @dataclasses.dataclass
  34. class Dataset:
  35.     """Stores features and their accompanying responses."""

  36.     features: np.ndarray
  37.     responses: np.ndarray

  38.     def __post_init__(self):
  39.         assert self.features.shape[0] == self.responses.shape[0]


  40. class LogisticRegressionModel:
  41.     """Predicts responses for a Dataset."""

  42.     def __init__(
  43.         self,
  44.         coefficients: np.ndarray,
  45.     ):
  46.         if coefficients.ndim != 1:
  47.             raise ValueError(f"Unexpected coefficient ndim (found {coefficients.ndim})")
  48.         self.coefficients = coefficients

  49.     def compute_probabilities(self, features: np.ndarray) -> np.ndarray:
  50.         return _compute_probabilities(features, self.coefficients)

  51.     def predict(self, dataset: Dataset, threshold: float = 0.5) -> np.ndarray:
  52.         probabilities = self.compute_probabilities(dataset.features)
  53.         return (probabilities > threshold).astype(np.int8)


  54. class LogisticRegressionFitter:
  55.     """Fits a Logistic Regression model using minibatch stochastic gradient descent."""

  56.     def __init__(
  57.         self,
  58.         hyperparameters: Hyperparameters,
  59.     ):
  60.         self.hyperparameters = hyperparameters
  61.         self.epoch_losses: list[float] = []

  62.     def fit(self, dataset: Dataset) -> LogisticRegressionModel:
  63.         """Returns a LogisticRegressionModel by fitting the supplied dataset"""
  64.         assert dataset.features.ndim == 2
  65.         num_instances, num_features = dataset.features.shape
  66.         coefficients = np.zeros(num_features)
  67.         for epoch in range(self.hyperparameters.epochs):
  68.             # Visit the feature rows in random order.
  69.             row_indices = np.argsort(
  70.                 np.random.uniform(low=0, high=1, size=num_instances), axis=0
  71.             )
  72.             # Mini-batches over the shuffled dataset.
  73.             shuffled_features = dataset.features[row_indices]
  74.             shuffled_responses = dataset.responses[row_indices]
  75.             for batch_index in range(
  76.                 int(num_instances / self.hyperparameters.batch_size)
  77.             ):
  78.                 batch_start = batch_index * self.hyperparameters.batch_size
  79.                 batch_end = batch_start + self.hyperparameters.batch_size
  80.                 batch_features = shuffled_features[batch_start:batch_end]
  81.                 batch_responses = shuffled_responses[batch_start:batch_end].reshape(
  82.                     (self.hyperparameters.batch_size, 1)
  83.                 )
  84.                 batch_predictions = _compute_probabilities(
  85.                     batch_features, coefficients
  86.                 ).reshape((self.hyperparameters.batch_size, 1))
  87.                 gradient = _compute_cross_entropy_loss_gradient(
  88.                     batch_features,
  89.                     batch_responses,
  90.                     batch_predictions,
  91.                 ) + self.hyperparameters.regularizer.gradiate_penalty(coefficients)
  92.                 coefficients -= self.hyperparameters.learning_rate * gradient

  93.             # Evaluate epoch loss.
  94.             y = dataset.responses.astype(RESPONSE_TYPE)
  95.             y_hat = _compute_probabilities(dataset.features, coefficients)
  96.             epoch_loss = _compute_cross_entropy_loss(y, y_hat) + self.hyperparameters.regularizer.loss_penalty(coefficients)
  97.             self.epoch_losses.append(epoch_loss)
  98.             logger.info(f"[{epoch}]\tLoss {epoch_loss:.7f}")
  99.         return LogisticRegressionModel(coefficients=coefficients)


  100. def _compute_probabilities(features: np.array, coefficients: np.array) -> np.array:
  101.     return _sigmoid(np.matmul(features, coefficients))


  102. def _sigmoid(z: np.array) -> np.array:
  103.     return 1 / (1 + np.exp(-z))


  104. def _compute_cross_entropy_loss(y: np.array, y_hat: np.array) -> np.array:
  105.     return np.mean(-y * np.log(y_hat) - (1 - y) * np.log(1 - y_hat))


  106. def _compute_cross_entropy_loss_gradient(
  107.     x: np.array, y: np.array, y_hat: np.array
  108. ) -> np.array:
  109.     residuals = (y_hat - y).reshape((-1, 1))
  110.     return (x * residuals).mean(axis=0)


  111. def main():
  112.     hyperparameters = Hyperparameters()
  113.     np.random.seed(hyperparameters.seed)
  114.     num_features = 5

  115.     dataset_generator = DatasetGenerator(num_features=num_features)
  116.     dataset = dataset_generator.generate(num_samples=hyperparameters.batch_size * 10)
  117.     fitter = LogisticRegressionFitter(hyperparameters=hyperparameters)
  118.     model = fitter.fit(dataset)
  119.     logger.info(
  120.         f"[🏁]\tCoefficients: {[round(c, 2) for c in model.coefficients.tolist()]}\tNorm: {np.linalg.norm(model.coefficients):.2f}"
  121.     )

  122.     num_heldout_samples = 100
  123.     heldout_dataset = dataset_generator.generate(num_samples=num_heldout_samples)
  124.     heldout_predictions = model.predict(heldout_dataset)
  125.     heldout_accuracy = calculate_accuracy(
  126.         responses=heldout_dataset.responses, predictions=heldout_predictions
  127.     )
  128.     logger.info(f"[🏁]\tHeldout accuracy: {heldout_accuracy}")

  129.     # Checks.
  130.     if monotonically_decreases_or_stabilizes(fitter.epoch_losses):
  131.         logger.info("[✅]\tEpoch losses decrease and stabilize during training.")
  132.     else:
  133.         logger.info("[❌]\tEpoch losses do not decrease or stablize during training.")
  134.     if heldout_accuracy > 0.9:
  135.         logger.info("[✅]\tAccuracy on heldout dataset is high enough.")
  136.     else:
  137.         logger.info("[❌]\tAccuracy on heldout dataset is not high enough.")


  138. # STOP READING HERE.
  139. # NO NEED TO READ BELOW HERE.


  140. class DatasetGenerator:
  141.     """
  142.     Creates sample datasets, inspired by sklearn's make_blobs.
  143.     """

  144.     def __init__(self, num_features: int = 10):
  145.         self.num_features = num_features
  146.         self.num_centers = 2
  147.         center_box = (-10.0, 10.0)
  148.         self.centers = np.random.uniform(
  149.             center_box[0], center_box[1], size=(self.num_centers, num_features)
  150.         )
  151.         self.cluster_std = np.full(len(self.centers), 1.0)

  152.     def generate(self, num_samples: int) -> Dataset:
  153.         X = []
  154.         y = []
  155.         num_samples_per_center = [
  156.             int(num_samples // self.num_centers)
  157.         ] * self.num_centers
  158.         for i in range(num_samples % self.num_centers):
  159.             num_samples_per_center[i] += 1
  160.         for i, (n, std) in enumerate(zip(num_samples_per_center, self.cluster_std)):
  161.             X.append(
  162.                 np.random.normal(
  163.                     loc=self.centers[i], scale=std, size=(n, self.num_features)
  164.                 )
  165.             )
  166.             y += [i] * n

  167.         X = np.concatenate(X)
  168.         y = np.array(y)

  169.         total_num_samples = np.sum(num_samples)
  170.         indices = np.arange(total_num_samples)
  171.         np.random.shuffle(indices)
  172.         return Dataset(
  173.             features=X[indices].astype(FEATURE_TYPE),
  174.             responses=y[indices].astype(RESPONSE_TYPE),
  175.         )


  176. def calculate_accuracy(responses: np.ndarray, predictions: np.ndarray) -> float:
  177.     return np.sum(responses == predictions) / predictions.shape[0]


  178. def monotonically_decreases_or_stabilizes(values: list[float]) -> bool:
  179.     return all(i >= j for i, j in zip(values[:-1], values[1:]))


  180. if __name__ == "__main__":
  181.     main()
复制代码
这是第一问的代码。

第二轮 coding:
给了一个图形处理的场景。
第一问实现一个image的sanitize_ima
您好!
本帖隐藏的内容需要积分高于 188 才可浏览
您当前积分为 0。
使用VIP即刻解锁阅读权限或查看其他获取积分的方式
游客,您好!
本帖隐藏的内容需要积分高于 188 才可浏览
您当前积分为 0。
VIP即刻解锁阅读权限 或 查看其他获取积分的方式
Unlock interview details and practice with AI
Popular Interview Questions from Top Companies
roject 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.


身在国内,被外企雷已经四个月了,还没有上岸,想着试试澳大利亚的机会还是没有抓住,面经分享给地里的人希望能帮助到需要的人也帮自己攒个人品了。求大米

本帖子中包含更多资源

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x

评分

参与人数 5大米 +14 收起 理由
KBLOSSOM + 1 很有用的信息!
小鲸鱼学呀学 + 1 赞一个
匿名用户-OUSUI + 10 欢迎分享你知道的情况,会给更多大米奖励!
vincent_great + 1 很有用的信息!
zhzhzhz1 + 1 赞一个

查看全部评分


上一篇:亚麻 OA
下一篇:Amazon AS Intern被拒Timeline
🔗
vincent_great 2024-4-30 04:35:17 | 只看该作者
全局:
这面的不是一般的难啊 。。。
回复

使用道具 举报

地里匿名用户
🔗
匿名用户-ZPAR2  2024-4-30 09:41:54 来自APP
已加米,写得太详细了谢谢楼主
我也在澳洲,canva确实算澳洲除了atlassian以外的本土大厂了
回复

使用道具 举报

全局:
感谢分享,很有用的信息
回复

使用道具 举报

🔗
Linon 2024-12-23 01:00:08 | 只看该作者
全局:
感谢分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表