반응형

출처 : 프로그래머스

 

코딩테스트 연습 - 디스크 컨트롤러

하드디스크는 한 번에 하나의 작업만 수행할 수 있습니다. 디스크 컨트롤러를 구현하는 방법은 여러 가지가 있습니다. 가장 일반적인 방법은 요청이 들어온 순서대로 처리하는 것입니다. 예를

programmers.co.kr

  • 디스크 컨트롤러
문제 설명

하드디스크는 한 번에 하나의 작업만 수행할 수 있습니다. 디스크 컨트롤러를 구현하는 방법은 여러 가지가 있습니다. 가장 일반적인 방법은 요청이 들어온 순서대로 처리하는 것입니다.

예를들어

- 0ms 시점에 3ms가 소요되는 A작업 요청
- 1ms 시점에 9ms가 소요되는 B작업 요청
- 2ms 시점에 6ms가 소요되는 C작업 요청

와 같은 요청이 들어왔습니다. 이를 그림으로 표현하면 아래와 같습니다.

한 번에 하나의 요청만을 수행할 수 있기 때문에 각각의 작업을 요청받은 순서대로 처리하면 다음과 같이 처리 됩니다.

- A: 3ms 시점에 작업 완료 (요청에서 종료까지 : 3ms)
- B: 1ms부터 대기하다가, 3ms 시점에 작업을 시작해서 12ms 시점에 작업 완료(요청에서 종료까지 : 11ms)
- C: 2ms부터 대기하다가, 12ms 시점에 작업을 시작해서 18ms 시점에 작업 완료(요청에서 종료까지 : 16ms)

이 때 각 작업의 요청부터 종료까지 걸린 시간의 평균은 10ms(= (3 + 11 + 16) / 3)가 됩니다.

하지만 A → C → B 순서대로 처리하면

- A: 3ms 시점에 작업 완료(요청에서 종료까지 : 3ms)
- C: 2ms부터 대기하다가, 3ms 시점에 작업을 시작해서 9ms 시점에 작업 완료(요청에서 종료까지 : 7ms)
- B: 1ms부터 대기하다가, 9ms 시점에 작업을 시작해서 18ms 시점에 작업 완료(요청에서 종료까지 : 17ms)

이렇게 A → C → B의 순서로 처리하면 각 작업의 요청부터 종료까지 걸린 시간의 평균은 9ms(= (3 + 7 + 17) / 3)가 됩니다.

각 작업에 대해 [작업이 요청되는 시점, 작업의 소요시간]을 담은 2차원 배열 jobs가 매개변수로 주어질 때, 작업의 요청부터 종료까지 걸린 시간의 평균을 가장 줄이는 방법으로 처리하면 평균이 얼마가 되는지 return 하도록 solution 함수를 작성해주세요. (단, 소수점 이하의 수는 버립니다)

제한 사항
  • jobs의 길이는 1 이상 500 이하입니다.
  • jobs의 각 행은 하나의 작업에 대한 [작업이 요청되는 시점, 작업의 소요시간] 입니다.
  • 각 작업에 대해 작업이 요청되는 시간은 0 이상 1,000 이하입니다.
  • 각 작업에 대해 작업의 소요시간은 1 이상 1,000 이하입니다.
  • 하드디스크가 작업을 수행하고 있지 않을 때에는 먼저 요청이 들어온 작업부터 처리합니다.
입출력 예jobsreturn
[[0, 3], [1, 9], [2, 6]] 9
입출력 예 설명

문제에 주어진 예와 같습니다.

  • 0ms 시점에 3ms 걸리는 작업 요청이 들어옵니다.
  • 1ms 시점에 9ms 걸리는 작업 요청이 들어옵니다.
  • 2ms 시점에 6ms 걸리는 작업 요청이 들어옵니다.
import heapq

def solution(jobs):
    answer = 0
    # [작업이 요청되는 시점, 작업의 소요시간]
    heapq.heapify(jobs)
    jobs_sort = sorted(jobs , key=lambda x : (x[1]))
    
    start = 0
    while jobs_sort:
        for idx, val in enumerate(jobs_sort):
            if jobs_sort[idx][0] <= start:
                start += jobs_sort[idx][1]
                answer += start - jobs_sort[idx][0]
                jobs_sort.pop(idx)
                break

            if idx == len(jobs_sort) - 1:
                start += 1

    return answer // len(jobs)

jobs = 	[[0, 3], [1, 9], [2, 6]]
solution(jobs)
# 테스트 20 만 성공

https://codermun-log.tistory.com/305

 

힙_디스크 컨트롤러_Python

문제 설명 하드디스크는 한 번에 하나의 작업만 수행할 수 있습니다. 디스크 컨트롤러를 구현하는 방법은 여러 가지가 있습니다. 가장 일반적인 방법은 요청이 들어온 순서대로 처리하는 것입

codermun-log.tistory.com

 

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

H-Index  (0) 2022.06.30
이중우선순위큐  (0) 2022.06.21
주식가격  (0) 2022.06.07
다리를 지나는 트럭  (0) 2022.06.02
베스트앨범  (0) 2022.05.19
반응형

출처 : 프로그래머스 

 

코딩테스트 연습 - 주식가격

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00

programmers.co.kr

문제 설명

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.

제한사항
  • prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
  • prices의 길이는 2 이상 100,000 이하입니다.
입출력 예pricesreturn
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]
입출력 예 설명
  • 1초 시점의 ₩1은 끝까지 가격이 떨어지지 않았습니다.
  • 2초 시점의 ₩2은 끝까지 가격이 떨어지지 않았습니다.
  • 3초 시점의 ₩3은 1초뒤에 가격이 떨어집니다. 따라서 1초간 가격이 떨어지지 않은 것으로 봅니다.
  • 4초 시점의 ₩2은 1초간 가격이 떨어지지 않았습니다.
  • 5초 시점의 ₩3은 0초간 가격이 떨어지지 않았습니다.

※ 공지 - 2019년 2월 28일 지문이 리뉴얼되었습니다.

 

처음에는 아무 생각 없이 for문을 두개 작성하였다. 실패가 나왔다. 

그다음 stack을 사용하였다 . => 시간초과 

마지막에 deque를 사용하였더니 통과하였다. 

from collections import deque
def solution(prices):
    answer = []
    queue = deque(prices)
    while queue:
        price = queue.popleft()
        cnt = 0
        for i in queue:
            cnt += 1
            if i < price:
                break
        answer.append(cnt)
    return answer

prices = [1, 2, 3, 2, 3]
solution(prices)

 

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

이중우선순위큐  (0) 2022.06.21
디스크 컨트롤러  (0) 2022.06.15
다리를 지나는 트럭  (0) 2022.06.02
베스트앨범  (0) 2022.05.19
[Lv.1] 하샤드 수  (0) 2022.05.06
반응형

출처 : 프로그래머스

 

트럭 여러 대가 강을 가로지르는 일차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 다리에는 트럭이 최대 bridge_length대 올라갈 수 있으며, 다리는 weight 이하까지의 무게를 견딜 수 있습니다. 단, 다리에 완전히 오르지 않은 트럭의 무게는 무시합니다.

예를 들어, 트럭 2대가 올라갈 수 있고 무게를 10kg까지 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서대로 최단 시간 안에 다리를 건너려면 다음과 같이 건너야 합니다.

경과 시간다리를 지난 트럭다리를 건너는 트럭대기 트럭

0 [] [] [7,4,5,6]
1~2 [] [7] [4,5,6]
3 [7] [4] [5,6]
4 [7] [4,5] [6]
5 [7,4] [5] [6]
6~7 [7,4,5] [6] []
8 [7,4,5,6] [] []

따라서, 모든 트럭이 다리를 지나려면 최소 8초가 걸립니다.

solution 함수의 매개변수로 다리에 올라갈 수 있는 트럭 수 bridge_length, 다리가 견딜 수 있는 무게 weight, 트럭 별 무게 truck_weights가 주어집니다. 이때 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 return 하도록 solution 함수를 완성하세요.

제한 조건

  • bridge_length는 1 이상 10,000 이하입니다.
  • weight는 1 이상 10,000 이하입니다.
  • truck_weights의 길이는 1 이상 10,000 이하입니다.
  • 모든 트럭의 무게는 1 이상 weight 이하입니다.

입출력 예

bridge_lengthweighttruck_weightsreturn

2 10 [7,4,5,6] 8
100 100 [10] 101
100 100 [10,10,10,10,10,10,10,10,10,10] 110

출처

※ 공지 - 2020년 4월 06일 테스트케이스가 추가되었습니다.

# bridge_length 다리 길이 2일 경우 2
def solution(bridge_length, weight, truck_weights):
    answer = 0
    bridge_truck = [0] * bridge_length # 다리를 건너는 트럭
    while len(bridge_truck) != 0:
        answer += 1
        bridge_truck.pop(0)
        if truck_weights:
            if sum(bridge_truck) + truck_weights[0] > weight:
                bridge_truck.append(0)
            else:
                truck_weight = truck_weights.pop(0)
                bridge_truck.append(truck_weight)
            #print(bridge_truck)
    return answer

bridge_length = 2
weight = 10
truck_weights = [7,4,5,6]
solution(bridge_length, weight, truck_weights)

 

 

참조 :

https://donis-note.medium.com/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%8B%A4%EB%A6%AC%EB%A5%BC-%EC%A7%80%EB%82%98%EB%8A%94-%ED%8A%B8%EB%9F%AD-python-8d03d1ac2a45

 

[프로그래머스] 다리를 지나는 트럭 — Python

다리를 지나는 트럭 — Python

donis-note.medium.com

 

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

디스크 컨트롤러  (0) 2022.06.15
주식가격  (0) 2022.06.07
베스트앨범  (0) 2022.05.19
[Lv.1] 하샤드 수  (0) 2022.05.06
124 나라의 숫자  (0) 2022.04.27
반응형

출처 : 프로그래머스

 

코딩테스트 연습 - 기능개발

프로그래머스 팀에서는 기능 개선 작업을 수행 중입니다. 각 기능은 진도가 100%일 때 서비스에 반영할 수 있습니다. 또, 각 기능의 개발속도는 모두 다르기 때문에 뒤에 있는 기능이 앞에 있는

programmers.co.kr

문제 설명

프로그래머스 팀에서는 기능 개선 작업을 수행 중입니다. 각 기능은 진도가 100%일 때 서비스에 반영할 수 있습니다.

또, 각 기능의 개발속도는 모두 다르기 때문에 뒤에 있는 기능이 앞에 있는 기능보다 먼저 개발될 수 있고, 이때 뒤에 있는 기능은 앞에 있는 기능이 배포될 때 함께 배포됩니다.

먼저 배포되어야 하는 순서대로 작업의 진도가 적힌 정수 배열 progresses와 각 작업의 개발 속도가 적힌 정수 배열 speeds가 주어질 때 각 배포마다 몇 개의 기능이 배포되는지를 return 하도록 solution 함수를 완성하세요.

제한 사항
  • 작업의 개수(progresses, speeds배열의 길이)는 100개 이하입니다.
  • 작업 진도는 100 미만의 자연수입니다.
  • 작업 속도는 100 이하의 자연수입니다.
  • 배포는 하루에 한 번만 할 수 있으며, 하루의 끝에 이루어진다고 가정합니다. 예를 들어 진도율이 95%인 작업의 개발 속도가 하루에 4%라면 배포는 2일 뒤에 이루어집니다.
입출력 예progressesspeedsreturn
[93, 30, 55] [1, 30, 5] [2, 1]
[95, 90, 99, 99, 80, 99] [1, 1, 1, 1, 1, 1] [1, 3, 2]
입출력 예 설명

입출력 예 #1
첫 번째 기능은 93% 완료되어 있고 하루에 1%씩 작업이 가능하므로 7일간 작업 후 배포가 가능합니다.
두 번째 기능은 30%가 완료되어 있고 하루에 30%씩 작업이 가능하므로 3일간 작업 후 배포가 가능합니다. 하지만 이전 첫 번째 기능이 아직 완성된 상태가 아니기 때문에 첫 번째 기능이 배포되는 7일째 배포됩니다.
세 번째 기능은 55%가 완료되어 있고 하루에 5%씩 작업이 가능하므로 9일간 작업 후 배포가 가능합니다.

따라서 7일째에 2개의 기능, 9일째에 1개의 기능이 배포됩니다.

입출력 예 #2
모든 기능이 하루에 1%씩 작업이 가능하므로, 작업이 끝나기까지 남은 일수는 각각 5일, 10일, 1일, 1일, 20일, 1일입니다. 어떤 기능이 먼저 완성되었더라도 앞에 있는 모든 기능이 완성되지 않으면 배포가 불가능합니다.

따라서 5일째에 1개의 기능, 10일째에 3개의 기능, 20일째에 2개의 기능이 배포됩니다.

※ 공지 - 2020년 7월 14일 테스트케이스가 추가되었습니다.

queue 방식

import math
from collections import deque

def solution(progresses, speeds):
    answer = []
    results = [math.ceil((100 - progresse) / speed) for (progresse,speed) in zip(progresses, speeds)]
    queue = deque(results)
    while queue:
        progresse = queue.popleft()
        cnt = 1
        while queue:
            progresse1 = queue.popleft()
            if progresse < progresse1:
                queue.appendleft(progresse1)
                break
            cnt += 1
        answer.append(cnt)
        

    return answer

progresses = [95, 90, 99, 99, 80, 99]
speeds = [1, 1, 1, 1, 1, 1]
# [1, 3, 2]
solution(progresses, speeds)

 

stack 방식

import math
from collections import deque

def solution(progresses, speeds):
    answer = []
    results = [math.ceil((100 - progresse) / speed) for (progresse,speed) in zip(progresses, speeds)]
    while results:
        progresse = results.pop(0)
        cnt = 1
        while results:
            progresse1 = results.pop(0)
            if progresse < progresse1:
                results.insert(0,progresse1)
                break
            cnt += 1
        answer.append(cnt)
        

    return answer

progresses = [95, 90, 99, 99, 80, 99]
speeds = [1, 1, 1, 1, 1, 1]
# [1, 3, 2]
solution(progresses, speeds)
반응형
반응형

출처 : 프로그래머스

 

코딩테스트 연습 - 베스트앨범

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가

programmers.co.kr

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.

  1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
  2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
  3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.

제한사항

  • genres[i]는 고유번호가 i인 노래의 장르입니다.
  • plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.
  • genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.
  • 장르 종류는 100개 미만입니다.
  • 장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.
  • 모든 장르는 재생된 횟수가 다릅니다.

입출력 예

genresplaysreturn

["classic", "pop", "classic", "classic", "pop"] [500, 600, 150, 800, 2500] [4, 1, 3, 0]

입출력 예 설명

classic 장르는 1,450회 재생되었으며, classic 노래는 다음과 같습니다.

  • 고유 번호 3: 800회 재생
  • 고유 번호 0: 500회 재생
  • 고유 번호 2: 150회 재생

pop 장르는 3,100회 재생되었으며, pop 노래는 다음과 같습니다.

  • 고유 번호 4: 2,500회 재생
  • 고유 번호 1: 600회 재생

따라서 pop 장르의 [4, 1]번 노래를 먼저, classic 장르의 [3, 0]번 노래를 그다음에 수록합니다.

※ 공지 - 2019년 2월 28일 테스트케이스가 추가되었습니다.

 

최종풀이 :

def solution(genres, plays):
    answer = []
    dic = {}
    for idx, genre in enumerate(genres):
        dic[genre] = dic.get(genre, 0) + plays[idx]
    #sorted(d.items(), key=lambda x: x[1], reverse=True)
    dic  = sorted(dic.items(), key = lambda x: x[1], reverse= True)
    #['pop', 'classic']
    genre_play = list(enumerate(list(zip(genres, plays))))
    # [(0, ('classic', 500)), (1, ('pop', 600)), (2, ('classic', 150)), (3, ('classic', 800)), (4, ('pop', 2500))]
    genre_play.sort( key = lambda x: x[1], reverse = True )
    # [(4, ('pop', 2500)), (1, ('pop', 600)), (3, ('classic', 800)), (0, ('classic', 500)), (2, ('classic', 150))]
    #print(genre_play)
    
    for key, value in dic:
        count = 0
        for (idx, (genre, play)) in genre_play:
            if genre == key:
                answer.append(idx)
                count += 1
                if count >= 2:
                    break
    return answer

genres = ["classic", "pop", "classic", "classic", "pop"]
plays = [500, 600, 150, 800, 600]
assert solution(genres, plays) == [3, 0, 1, 4], solution(genres, plays)
처음에는  3번, 4번 , 15번 만 통과하였다. 
dic  = sorted(dic.keys(), key = lambda x: x[1], reverse= True)
로 해주어셔 그렇다. 

dic  = sorted(dic.items(), key = lambda x: x[1], reverse= True)

로 수정하였더니 통과 하였다. 

 

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

주식가격  (0) 2022.06.07
다리를 지나는 트럭  (0) 2022.06.02
[Lv.1] 하샤드 수  (0) 2022.05.06
124 나라의 숫자  (0) 2022.04.27
튜플  (0) 2022.04.27
반응형

CDistNet: Perceiving Multi-Domain Character Distance for Robust Text Recognition

 

https://arxiv.org/abs/2111.11011

 

CDistNet: Perceiving Multi-Domain Character Distance for Robust Text Recognition

The attention-based encoder-decoder framework is becoming popular in scene text recognition, largely due to its superiority in integrating recognition clues from both visual and semantic domains. However, recent studies show the two clues might be misalign

arxiv.org

Abstract

attention-based encoder-decoder framework는 scene text recognition에서 인기가 있는 이유는 visual and semantic domains으로 부터 recognition clues(힌트)를 통합하는데 있어서 성능이 우월하다. ⇒ scene text recognition 의 trend이다.

하지만 최근의 연구는 visual and semantic 양쪽의 clues가 특히 어려운 text에서 서로 잘 연결이 안되고 그것을 완화하기 위해서 character position constraints 을 소개한다. ⇒ 한계점

어떤한 성공에도 불구하고 의미 있는 지역적인 image regions와 a content-free positional embedding은 거의 안정적으로 연결되지 않는다.

이 논문은 visual and semantic related position encoding 새로운 모듈을 소개 ⇒ Multi-Domain Character Distance Perception (MDCDP)이라고 하는 모듈

MDCDP는 attention mechanism에 따라 visual and semantic features 두개 다 query로 사용하기 위해 positional embedding을 사용한다.

visual and semantic distances 를 모두 설명하는 positional clue를 자연스럽게 encoding한다.

우리는 새로운 architecture CDistNet이라고 하고 MDCDP를 여러개 쌓은 것 이며 좀 더 정확한 distance modeling이 가능하다.

따라서 다양한 어려움이 제시되더라도 visual-semantic alignment 이 잘 구축된다.

two augmented datasets and six public benchmarks

시각화는 또한 CDistNet이 visual and semantic domains 모두 에서 적절한 attention localization를 달성함을 보여준다.

소스코드 위치 : https://github.com/ simplify23/CDistNet. 소스코드는 초반에 없었는데 공개되였다.

 

1. Introduction

최근 몇년 동안 엄청나는 많은 연구가 수행되었음에도 Scene text recognition은 여러가지 문제에 직면해있다. 예를 들어, complex text deformations, unequally distributed characters, cluttered background, etc. ⇒ key issue

최근에는 attention-based encoder-decoder methods가 이 task에서 인상적인 영향을 보여왔다.

하지만 최근 연구[38]에서 는 두가지 잘못 인식된 예와 같이 흔치 않는 정형화 되지 않는 text에서 mismatch가 쉽게 일어난다. Fig.1 (a)참조 .

선행 연구에서 mismatch 발생한 원인

1). visual clue가 약할 때 visual counterpart에 대해서 semantic clue가 제대로 찾지 못한다.

2). 길이가 long text에서 많이 일어난다. text 길이가 길면 semantic feature가 점점 강화되면서 완전히 압도가 된다.

⇒ attention drift

위의 문제로 , mismatch를 완화하기 위하여 character position을 사용하여 연구를 진행한다 . sinusoidal-like positional embedding [6,29] or others [35,43,44]으로 encoding하였다.

이런 전략으로 문제는 좀 해결할 수 있으지만 [29, 44]여기에서는 content-free positional embedding을 사용하였기 때문에 visual feature가 character position하고 안정적으로 연관짓기가 어려웠다. 게다가 이미지 위치에 대한 character position에 대한 위치도 정해놓지 못하고 content-free positional embedding이 오히려 position order에 대한 제약만 주었다.

content-aware receptor를 해서 인식하는 것이 아니라 position order에 대한 제안만 주었다.

게다가 position and semantic space 관계는 아예 무시를 해버린다.

 

이 논문에서는 앞에서 언급된 이슈들을 극복하기 위해서 Multi Domain Character Distance Perception (MDCDP) 이라고 하는 새로운 module을 개발하였다.

기존의 연구 [34, 44] 와 유사하게 fixed positional embedding이 초기화 된다.

하지만 다른 점은 encoder가 position embedding하고 나서 그리고 visual and semantic features가 self-attention enhancement를 걸친다. 그리고 나서 비로서 query vector로 사용이 된다.

two enhanced features가 일종의 visual and semantic distance-aware representation 이 된다.

이전 정보 가 다음 MDCDP의 query vector로 들어간다. 그렇게 하면 좀 더 attention-focused visual-semantic alignment 가 얻어진다.

이런 idea를 따라서 CDistNet이라는 architecture를 제안한다.

여러개 MDCDP가 쌓인 것이고 정확한 distance modeling이 가능하도록 한다.

이렇게 하면 complex character이 spatial layouts 이 인식하는데 도움이 된다.

(b) HA-IC13 and CA-IC13 datasets are created by horizontal and curved stretching ICDAR2013 with various scales.

(c) We develop CDistNet that perceives multi-domain character distance better by position-related joint encoding. Compared with baseline, the accuracy margin becomes larger as the deformation severity rises.

 

 

3가지 기여도가 이다.

  1. MDCDP visual and semantic features모두 positional feature 를 사용 할 수 있게 만든다.
  2. CDistNet stacks several MDCDP 어려운 text를 recognizing하는데 이점이 있다.
  3. we carry out extensive experiments with different configurations and compare CDistNet with existing methods.

2. Related Work

2.1. Semantic-free Methods

RNN and CTC loss

semantic정보를 무시 하고

visual feature만 가지고 modeling한다.

2.2. Semantic-Enhanced Methods

visual feature을 강화하기 위해 semantic clue를 활용하고 attention framework와 함께 encoder decoder를 사용하는 것을 강조

Transformer [34], a powerful model in capturing global spatial dependence, many variants [23, 29, 37] were developed with improved accuracy.

semantic loss를 도입한 것도 있고

semantic feature를 사용하는데 visual feature를 강화하는

ABINet은 별도의 language model을 사용하고 나중에 합쳐서 사용

하지만 misalignment문제가 여전히 남아 있고 attention drift

2.3. Position-Enhanced Methods

position도 고려하겠다.

character position encoding to ease the recognition

advanced rectification models 개발하였지만 , rectification 자체로는 서로 different clues에서 synergistic사용하는데 실패하였다.

Transformer-based models attention mechanism was non-local global하게 한다.

sinusoidal positional embedding

learnable embedding

segmentation map : ensure that characters

RobustScanner [44] proposed a position enhancement branch along with a dynamical fusion mechanism and achieved impressive results.

RobustScanner content-free positional embedding that hardly built a stable correspondence between positions and local image regions

CDistNet에서는 positional embedding을 visual and semantic features 양족에다 주입해서 multi-domain distance aware modeling 수립

 

3. Methodology

end-to-end trainable network

attention-based encoder-decoder framework

encoder : three branches : encoding visual, positional and semantic information

decoder : three kinds of information are fused by a dedicated designed MDCDP module, positional branch is leveraged to reinforce both visual and semantic branches and generate a new hybrid distance-aware positional embedding.

The generated embedding, which records the relationship among characters in both visual and semantic domains, is used as the positional embedding of the next MDCDP. (다음 MDCDP input으로 사용)

It is thus conducive to generating a attention-focused visual-semantic alignment.

The MDCDP module is stacked several times in CDistNet to achieve a more precise distance modeling.

At last, characters are decoded sequentially based on the output of the last MDCDP module.

마지막 MDCDP module의 output이 문자를 순차적으로 decoding된다.

3.1. Encoder

Visual Branch. TPS를 사용해서 rectify 을 먼저 한다.

Backbone : ResNet-45 and Transformer units , both local and global spatial dependencies를 captures 한다.

ResNet45

Transformer units are three-layer self-attention encoders with 1024 hidden units per layer

T : TPS block

R represents ResNet-45, ResNet-45 downsamples both the width and height to 1/8 of the original size

τ is the Transformer unit

Semantic Branch.

previously seen characters during training

이전에 decode된 character들이 input으로 들어간다.

test 단계에서, 이전에 decode된 character들은 각 time step에서 update되는 current semantic feature으로 encode된다.

Embedding of the start token is used when decoding the first character.

L을 decoding할려고 하면 input은 없으면 안되서 start token으로 한다.

Positional Branch.

text의 문자 위치를 endode한다.

먼저 one-hot vector로 만든다. → same sinusoidal positional embedding

 

3.2. MDCDP

MDCDP module is formulated on the decoder side and benefit the recognition

3가지 parts로 구성이 되여있다.

self-attention enhancement for positional feature reinforcement

cross-branch interaction that utilizes positional feature to query both the visual and semantic branches, obtaining positional-enhanced representations

dynamic shared fusion to get a visual and semantic joint embedding

Self-Attention Enhancement (SAE)

encoder에서 positional embedding을 주면 SAE 가지고 embedding을 강화한다. multi-head self-attention block한개인 vanilla Transformer에서 다 빼고 하나인 것을 하고 self-attention을 한다.

dimension도 줄였다.

이 방식은 upper triangular mask 이고 

반대로 된 것은 lower triangular mask이다.

 

np.triu() ⇒ upper triangular mask : mask is applied to the query vector of the self-attention block to prevent from ”seeing itself”, or saying, leaking information across time steps. 다음 정보는 보면 안된다.

np.tril() ⇒ lowertriangular mask

 

RobustScanner내용

before using the positional embedding to query the visual feature 이러한 enhancement 는 사용하지 않는다. The query vector is always fixed in different character sequences. 바뀐 것이 없다.

반면에 , our enhancement enables a more targeted positional embedding learning.

Cross-Branch Interaction (CBI)

positional embedding is treated as the query vector

visual and semantic branches in parallel

When applying to the visual branch, it uses previous decoded character locations to search the position of the next character in the text image. CBI-V

While applying to the semantic branch, it models the semantic affinities between previous decoded characters and current positional clue. CBI-S.

Both branches have been reinforced after the interactions.

A similar upper triangular mask is also applied to the semantic branch to prevent information leaks due to its dynamical update nature.

이전 연구에서는 semantic feature가 query 로 들어가고

RobustScanner position에서 추가적인 query를 visual 쪽에 다 query를 얻은 것이다. position to visual and enables a positional-enhanced decoding.

하지만 , 우리는 semantic branch는 그대로 둔다. 대조적으로, we formulate the interactions as the positional-based intermediate enhancement to both visual and semantic domains. It reinforces not only visual but also semantic features and can be understood as delineating the multi-domain character distance.

Dynamic Shared Fusion (DSF).

two positional-enhanced features as input

visual 과 semantic

channel방향으로 concatenated 해서 하는데 channel이 2배가 된 hybrid feature가 된다.

→ 그 다음 다시 1 × 1 convolution 을 해서 절반으로 줄인다.

→ 그 다음 gating mechanism을 사용 transformed weight matrices

→ both visual and semantic features element-wisely

→ dynamic fusion

ABINet 

 

 

channel이 2C였다가 C로 줄어든다.

특이한 점은 the weights are shared among different MDCDP modules. As a consequence, DSF not only decouples the feature fusion with the previous attention learning, but also eases the network modeling.

 

4. Experiments

4.1. Datasets

three kinds of datasets :

two synthetic datasets for model training MJSynth (MJ) [10] and SynthText (ST) [7]

데이터 셋 sample

https://arxiv.org/pdf/1904.01906.pdf

two augmented datasets for model verification

HA-IC13 and CA-IC13 two augmented datasets created from ICDAR2013

simulate the horizontal (HAIC13) and curved (CA-IC13) stretching with scales from 1 (the smallest deformation) to 6 (the largest deformation) with interval of 1 using the data augmentation tool in [21]

postprocessing exception 것을 처리 하기 위한 것

6배 정도 많다.

six widely used public datasets for both ablation study and comparison with existing methods.

ICDAR2013 (IC13) [13], Street View Text (SVT) [36], IIIT5k-Words (IIIT5k) [24], ICDAR2015 (IC15) [12], SVT-Perspective (SVTP) [26] and CUTE80 (CUTE) [28]

The first three mainly contain regular text while the rest three are irregular.

4.2. Implementation details

We resize the input images to 32×128 and employ data augmentation such as image quality deterioration, color jitter and geometry transformation.

 Transformer 확인 

transformer의 learning rate와 같다.

To reduce the computational cost, we shrink the transformer units employed, where dimension of the MLP layer is reduced from 2048 to 1024 in encoder, and from 2048 to 512 in decoder.

beam search

4.3. Ablation study

 

 

 

 

The number of MDCDP modules considered.

layer를 많이 쌓으면 쌓을 수록 computational cost가 증가한다.

Therefore the MDCDP modules in CDistNet are empirically set to 3.

The effectiveness of SAE.

self attention enhancement는 position branch 에 사용

The effectiveness of CBI.

The result basically validates two hypotheses.

First, imposing the positional clue is helpful.

Second, it is effective to query the semantic feature by using the positional clue, which perceives the semantic affinities between previous decoded characters and current position.

The effectiveness of DSF.

DSF outperforms static-based fusions (Add and Dot) as well as the scheme that not sharing weights among MDCDP modules.

 

 

 

 

 

 

 

 

4.4. Model Verification

Contribution of the positional utilization.

We first explain how the methods are modified.

CDistNet w/o Sem

Transformer* visual branch를 강화

RobustScanner* Transformer unit to replace the raw ”CNN+LSTM” implementation

CDistNet

With the modifications above, accuracy

gains from the position modeling can be quantitatively evaluated.

positional utilization이 중요

Performance on augmented datasets.

HAIC13 and CA-IC13 are simulated with different levels of horizontal and curved deformations.

It clearly verifies the advantage of CDistNet in recognizing difficult text.

Decoding Visualization.

attention map based on the positional-enhanced visual branch and give some examples in Fig.6

It again indicates the superiority of the proposed MDCDP module.

 

 

 

 

 

semantic affinities between previous decoded characters and current position in Fig.7

Analysis of good and bad cases.

good: we can conclude that CDistNet retains powerful and universal recognition capability with the existence of various difficulties, e.g., diverse text shapes, blur, distortions, etc.

bad : We also list some bad cases in Fig.9. The failures can be summarized as three categories mainly, multiple text fonts (cocacola, quilts), severe blur (coffee) and vertical text (garage). Most of them are even undistinguishable by humans and they are common challenges for modern text recognizers.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4.5. Comparisons with Existing Methods

five datasets including IC13, SVT, IIIT5K, IC15 and SVT-P when trained based on the two synthetic datasets.

irregular text datasets

 

 

 

5. Conclusion

extreme irregular text, we have presented the MDCDP module which utilizes positional feature to query both visual and semantic features within the attention-based encoder-decoder framework.

both visual and semantic domains.

MDCDP module

eight datasets that successfully validate our proposal.

The result on augmented datasets shows larger accuracy margin is observed as the severity of deformation increases.

ablation studies

state-of-the-art accuracy when compared with existing methods on six standard benchmarks.

In addition, the visualization experiments also basically verify that superior attention localization are obtained in both visual and semantic domains.

반응형
반응형

출처 : 프로그래머스

 

코딩테스트 연습 - 하샤드 수

양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하

programmers.co.kr

문제 설명

양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요.

제한 조건
  • x는 1 이상, 10000 이하인 정수입니다.
입출력 예arrreturn
10 true
12 true
11 false
13 false
입출력 예 설명

입출력 예 #1
10의 모든 자릿수의 합은 1입니다. 10은 1로 나누어 떨어지므로 10은 하샤드 수입니다.

입출력 예 #2
12의 모든 자릿수의 합은 3입니다. 12는 3으로 나누어 떨어지므로 12는 하샤드 수입니다.

입출력 예 #3
11의 모든 자릿수의 합은 2입니다. 11은 2로 나누어 떨어지지 않으므로 11는 하샤드 수가 아닙니다.

입출력 예 #4
13의 모든 자릿수의 합은 4입니다. 13은 4로 나누어 떨어지지 않으므로 13은 하샤드 수가 아닙니다.

 

def solution(x):
    answer = (x % sum(list(map(int, str(x))))) == 0
    return answer

x = 11
solution(x)

3점을 받았다. 

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

다리를 지나는 트럭  (0) 2022.06.02
베스트앨범  (0) 2022.05.19
124 나라의 숫자  (0) 2022.04.27
튜플  (0) 2022.04.27
위장  (0) 2022.04.21
반응형

출처 : 프로그래머스

 

코딩테스트 연습 - 124 나라의 숫자

 

programmers.co.kr

124 나라가 있습니다. 124 나라에서는 10진법이 아닌 다음과 같은 자신들만의 규칙으로 수를 표현합니다.

  1. 124 나라에는 자연수만 존재합니다.
  2. 124 나라에는 모든 수를 표현할 때 1, 2, 4만 사용합니다.

예를 들어서 124 나라에서 사용하는 숫자는 다음과 같이 변환됩니다.

10진법124 나라10진법124 나라

1 1 6 14
2 2 7 21
3 4 8 22
4 11 9 24
5 12 10 41

자연수 n이 매개변수로 주어질 때, n을 124 나라에서 사용하는 숫자로 바꾼 값을 return 하도록 solution 함수를 완성해 주세요.

제한사항

  • n은 500,000,000이하의 자연수 입니다.

입출력 예

nresult

1 1
2 2
3 4
4 11
def solution(n):
    answer = ''
    number = [1, 2, 4]
    numbers = []
    n_ = n
    while n > 3:
        div, mod = divmod(n, len(number))
        if mod == 0:
            numbers.insert(0, 3)
            n = div - 1
        else:
            numbers.insert(0, mod)
            n = div
    numbers.insert(0, n)
    #print(n_, n, numbers, [str(number[i-1]) for i in numbers])
    answer= "".join([str(number[i-1]) for i in numbers])
    return answer

for n in range(1, 17):
    print(n, solution(n))
    solution(n)

반응형

'문제 > 프로그래머스' 카테고리의 다른 글

베스트앨범  (0) 2022.05.19
[Lv.1] 하샤드 수  (0) 2022.05.06
튜플  (0) 2022.04.27
위장  (0) 2022.04.21
동물 수 구하기_MySQL  (0) 2022.04.17

+ Recent posts