Входной файл: | Стандартный вход | Ограничение времени: | 1 сек | |
Выходной файл: | Стандартный выход | Ограничение памяти: | 512 Мб |
Пусть задан некоторый язык, описываемый множеством слов W, |W| = m, m ∈ N. Требуется построить наивный байесовский классификатор f: B↦ C = {i}k − 1i = 0, где {0, 1}m ⊇ B = ⋃l ∈ N,μ ∈ Wl{δw(μ)|w ∈ W} — множество представлений всех возможных сообщений составленных на языке W в виде мешка слов, δw — мера Дирака, δx(A) = {1,x ∈ A,0,x ∉ A..
При этом процесс классификации происходит следующим образом
Первая строка входного файла содержит натуральные числа n, m, k — количество сообщений, мощность языка и количество классов соответственно. В каждой их следующих n строк содержится m чисел 0 или 1 и одно натуральное число ci — представление сообщения в виде мешка слов и значение его класса.
Выходной файл должен содержать n натуральных чисел — предсказанное значение класса каждого сообщения на момент его получения.
10 ⩽ n ⩽ 7500
8 ⩽ m ⩽ 100
2 ⩽ k ⩽ 10
№ | Стандартный вход | Стандартный выход |
---|---|---|
1 |
|
|
Входной файл: | Стандартный вход | Ограничение времени: | 1 сек | |
Выходной файл: | Стандартный выход | Ограничение памяти: | 512 Мб |
Пусть заданы 4 набора точек: squares, circles, moons, spirals, которые можно скачать здесь.
Требуется на языке Python реализовать 4 функции,
преобразующие соответствующие наборы точек так,
чтобы они были идеально разделимы линейным
методом опорных векторов,
а именно sklearn.svm.SVC(kernel='linear')
.
import numpy as np
def transform_squares(X: np.ndarray) -> np.ndarray:
pass
def transform_circles(X: np.ndarray) -> np.ndarray:
pass
def transform_moons(X: np.ndarray) -> np.ndarray:
pass
def transform_spirals(X: np.ndarray) -> np.ndarray:
pass
При решении задачи запрещено использовать условные операторы и операторы сравнения.
Каждая функция принимает двумерный np.array
,
имеющий размеры (1200, 2).
Функции проверяются в порядке их определения в задаче.
Результатом работы функции должен являться двумерный массив преобразованных точек, имеющий тот же размер, что и исходный.
Входной файл: | input.jpg | Ограничение времени: | 2 сек | |
Выходной файл: | output.txt | Ограничение памяти: | 512 Мб |
Требуется реализовать на языке Python набор функций, выполняющие этапы применения оператора Кэнни:
import numpy as np
from typing import Tuple
def gaussian_blur(img: np.ndarray, kernel: Tuple[int, int], sigma: float) -> np.ndarray:
'''Blurs an image using Gaussian filter.
Arguments:
img: input image, a 2d np.ndarray.
kernel: gaussian kernel size.
sigma: gaussian kernel standard deviation.
Returns:
Blurred image, a 2d np.ndarray of the same size and dtype as `img`.
'''
pass
def magnitude_and_direction(img: np.ndarray, kernel: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
'''Applies a filter to the image and computes magnitude and direction of the gradient.
The filter is applied using 'reflect' mode for border pixels, i.e. dcb|abcd|cba
Arguments:
img: input image, a 2d np.ndarray.
kernel: the filter kernel, a 2d np.ndarray with odd dimension sizes.
The kernel is applied over x dimension, kernel.T is applied over y
Returns:
Magnitude and direction of the gradient, two 2d np.ndarray objects of the same size and dtype as `img`.
The direction values lie in range [0, 2 * pi].
'''
pass
def edge_thinning(magnitude: np.ndarray, direction: np.ndarray) -> np.ndarray:
'''Performs edge thinning step of Canny algorithm using 0°, 45°, 90°, 135°, 180° (=0°) gradient direction
as described here https://en.wikipedia.org/wiki/Canny_edge_detector#Gradient_magnitude_thresholding_or_lower_bound_cut-off_suppression.
If the angle is equally close to two groups, the group with lower angle value is selected.
Arguments:
magnitude: magnitude of image gradient, a 2d np.ndarray.
direction: direction of image gradient, a 2d np.ndarray.
Returns:
Boolean mask of suppressed pixels (False if a pixel is suppresed, True if preserved), a 2d np.ndarray of the same size as `magnitude` and dtype bool.
'''
pass
def edge_tracking(magnitude: np.ndarray, mask: np.ndarray, low_threshold: float, high_threshold: float) -> np.ndarray:
'''Performs edge tracking step of Canny algorithm. The thresholds are inclusive.
Arguments:
magnitude: magnitude of image gradient, a 2d np.ndarray.
mask: pixel suppression mask, obtained by edge_thinning function.
low_threshold: weak pixel threshold.
high_threshold: strong pixel threshold.
Returns:
A 2d np.ndarray of the same size as `magnitude` and dtype bool, representing detected edges.
'''
pass
Код решения должен содержать только импортируемые модули, определение и реализацию функций.
№ | Входной файл (input.jpg ) |
Выходной файл (output.txt ) |
---|---|---|
1 |
input.jpg img = cv.imread('input.jpg')
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY).astype(float)
blur = gaussian_blur(img, (5, 5), 1)
magnitude, direction = magnitude_and_direction(blur, np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]))
mask = edge_thinning(magnitude, direction)
edges = edge_tracking(magnitude, mask, 0.1 * np.max(magnitude), 0.2 * np.max(magnitude))
cv.imwrite('sample.png', edges.astype(int) * 255)
|
sample.png |
Входной файл: | Стандартный вход | Ограничение времени: | 1 сек | |
Выходной файл: | Стандартный выход | Ограничение памяти: | 512 Мб |
Требуется реализовать на языке Python класс, описывающий полносвязный слой нейронной сети:
import numpy as np
from typing import Optional, Tuple, Union
class Dense:
"""Implements fully-connected layer"""
def __init__(self, n_in: int, n_out: int, use_bias: bool = True):
"""Initializes Dense layer.
The weights are initialized using uniformly distributed values in range [-1, 1]. Bias vector is not initialized if `use_bias` is False.
Weigths matrix has the shape (`n_in`, `n_out`), bias vector has the shape (`n_out`, ).
Arguments:
n_in: Positive integer, dimensionality of input space.
n_out: Positive integer, dimensionality of output space.
use_bias: Whether the layer uses a bias vector."""
pass
@property
def weights(self) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray]:
"""Returns weights used by the layer."""
pass
@property
def input(self) -> np.ndarray:
"""Returns the last input received by the layer"""
pass
def __call__(self, x: np.ndarray) -> np.ndarray:
"""Performs the layer forward pass.
Arguments:
x: Input array of shape (`batch_size`, `n_in`)
Returns:
An array of shape (`batch_size`, `n_out`)"""
pass
def grad(self, gradOutput: np.ndarray) -> tuple[np.ndarray, tuple[np.ndarray, np.ndarray]] | tuple[np.ndarray, tuple[np.ndarray]]:
"""Computes layer gradients
Arguments:
gradOutput: Gradient of loss function with respect to the layer output, an array of shape (`batch_size`, `n_out`).
Returns:
A tuple object:
Gradient of loss function with respect to the layer input, an array of shape (`batch_size`, `n_in`)
Gradient of loss function with respect to the layer's weights:
An array of shape (`n_in`, `n_out`).
Optional array of shape (`n_out`, )."""
pass
Для реализации класса разрешено использовать только модуль numpy
.
Код решения должен содержать только импортируемые модули, определение и реализацию класса.