달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2021. 2. 9. 08:02

현대차,'애플카' 협력 중단 NEOgram/Issue2021. 2. 9. 08:02

728x90
반응형

지켜봐야 할 것 같다.

 

www.hankookilbo.com/News/Read/A2021020809430003077

 

 

현대차그룹 '애플카' 공동개발 일단 '정지'... "협상 주도권 싸움인 듯"

연초부터 메가톤급으로 전해졌던 현대자동차그룹과 애플의 ‘애플카’ 공동 개발 논의가 중단됐다. 자율주행 전기차종으로 알려진 애플카는 글로벌 기업인 양사의 첫 합작품이란 점에서 세간

www.hankookilbo.com

© 제공: 한국일보

연초부터 메가톤급으로 전해졌던 현대자동차그룹과 애플의 ‘애플카’ 공동 개발 논의가 중단됐다. 자율주행 전기차종으로 알려진 애플카는 글로벌 기업인 양사의 첫 합작품이란 점에서 세간의 관심을 끌었다. 일각에선 물밑 접촉을 통해 양 사가 재차 협력에 나설 가능성도 제기하고 있지만 양측의 입장 차이가 공식적으로 확인된 만큼, 장담하긴 어려운 형편이다.

현대차와 기아, 현대모비스는 8일 전자공시를 통해 “다수의 기업으로부터 자율주행 전기차 관련 공동개발 협력 요청을 받고 있으나, 초기단계로 결정된 바 없다”며 “애플과 자율주행차량 개발에 대한 협의를 진행하지 않고 있다”고 밝혔다.

 

일단 현대차그룹은 협상 중단 이유에 대해선 함구하고 있다. 현대차그룹 관계자는 “애플과 관련된 내용은 공시에서 밝힌 것 이외에는 어떠한 내용도 확인해 줄 수 없다”고 입을 다물었다. 양 사의 애플카와 관련된 논의 중단은 협상 테이블에서의 주도권 다툼에서 비롯됐을 것이란 관측이 우세하다. 과거 애플의 해외 스마트폰 시장 진출 과정을 살펴보면 현지 이동통신업체나 부품 협력사 선정 과정에서 수 차례의 협상 결렬과 재논의 등을 반복해왔다. 애플은 이 과정에서 언제나 유리한 고지를 점령했다.

 

 

애플은 현대차그룹 외에도 미국의 GM, FCA-PSA, 일본의 도요타, 닛산, 혼다, 마쓰다, 스바루, 중국의 폭스콘-지리차 등 10여개 완성차 업체와 애플과 관련 논의를 진행하고 있다. 하지만 이들 중 애플이 원하는 △대량생산 △수준 높은 조립 △전기차 전용 플랫폼 △납품단가 등의 조건을 모두 맞출 수 있는 곳은 제한적이다.

 

고태봉 하이투자증권 리서치센터장은 “유럽은 낮은 단가를 맞추기 힘들고, 일본차 업체들은 전기차 분야 기술력이 부족하고, 중국은 무역갈등이 걸림돌이 되는 등 우리나라 기업의 경쟁력이 앞선다고 볼 수 있다”며 “애플카가 단순한 전기차가 아니라, 자율주행 기능을 갖춘 차세대 ‘모빌리티(이동수단)’으로 등장이 예상되는 가운데 현대차그룹을 주요 협상 대상으로 삼고 있다는 것은, 관련 기술력을 공식적으로 인정받은 것으로도 볼 수 있다”고 전했다.

 

현대-애플카 관련주

현대차

기아차

현대위아

현대모비스

현대비앤지스틸

 

등등..

728x90
반응형

'NEOgram > Issue' 카테고리의 다른 글

머스크, 하늘 나는 차세대 전기차  (0) 2021.02.13
2021-02-10 (마감 시황)  (0) 2021.02.10
공매도+1  (0) 2021.02.07
공매도  (0) 2021.02.06
박셀바이오 2021-01-04 (월)  (0) 2021.01.04
:
Posted by 패치#노트
2021. 2. 7. 16:51

SK바이오사이언스 상장 추진 Recycle2021. 2. 7. 16:51

728x90
반응형

http://www.dailymedi.com/detail.php?number=866037&thread=22r05

데일리메디 SK바이오사이언스

보건의료문화를 선도하는 데일리메디 [데일리메디 양보혜 기자] 백신 전문기업 SK바이오사이언스가 내달 상장을 목표로 본격적인 공모 절차에 돌입한다. SK바이오사이언스(대표 안재용)는 코스

www.dailymedi.com

 
https://www.skbioscience.co.kr/kr/main

SK 바이오사이언스

SK bioscience News SK바이오사이언스, 증권신고서 제출.. 3월 코스피 상장 목표 SK바이오사이언스 연구원이 백신 개발을 위한 R&D를 진행하고 있다4일 한국거래소 상장예비심사 승인.. 내달 9~10일 공모

www.skbioscience.co.kr

http://www.dailymedi.com/detail.php?number=866037&thread=22r05

https://imgnews.pstatic.net/image/015/2021/02/05/0004495625_001_20210206134405617.jpg?type=w430

 


SK바이오사이언스는 2018년 SK케미칼의 백신 사업부문이 물적분할해 설립됐다. 독감, 대상포진 백신 등으로 잘 알려져 있지만 최근에는 코로나19 백신으로 주목받고 있다. 지난해 영국 아스트라제네카와 코로나19 백신 수탁생산(CMO) 계약, 미국 노바백스와 코로나19 백신 수탁개발생산(CDMO) 계약을 맺었다. 자체 개발 중인 코로나19 백신 두 종류도 최근 임상 단계에 들어갔다.

지난달 질병관리청으로부터 ‘코로나19 백신 유통관리체계 구축·운영 사업’ 수행기관으로 선정됐다. 이에 따라 회사는 아스트라제네카, 얀센, 화이자 백신을 비롯해 백신 구매를 위한 국제 프로젝트인 코박스 퍼실리티(COVAX facility) 백신 물량의 유통·보관을 담당한다. 또 정부가 이달 노바백스 백신 2000만 명분을 선구매하기로 하면서 SK바이오사이언스는 안정적인 매출처를 하나 더 확보하게 됐다.
관련주
SK케미칼

728x90
반응형
:
Posted by 패치#노트
2021. 2. 7. 09:40

공매도+1 NEOgram/Issue2021. 2. 7. 09:40

728x90
반응형

https://n.news.naver.com/article/001/0012188878

개미에 삼전·셀트리온 등 공매도 확대…수수료·상환기간 '벽'

대주물량 2조~3조원 확보했지만 수요 미지수…금융위, 개선 대책 발표 (서울=연합뉴스) 임수정 김연숙 기자 = 금융당국이 오는 5월 공매도를 부분 재개하며 개인 공매도 활성화를 위한 '통합 대주

n.news.naver.com

특히 최대 4%에 달하는 수수료와 60일 안팎의 짧은 주식 상환 기간 등이 개인에게 부담이 될 수 있다는 지적에 금융당국이 해결책을 고심 중이다.

7일 금융당국과 금융투자업계에 따르면 금융위는 오는 5월 3일 공매도 부분 재개 시 코스피 200 및 코스닥150을 구성하는 모든 종목에서 개인 대주가 가능할 수 있도록 물량을 확보 중이다.

금융당국 관계자는 "공매도 재개가 허용되는 종목에 한해서는 모든 물량을 확보하는 게 목표"라고 말했다.

삼성전자와 셀트리온헬스케어 등 국내 주식시장을 대표하는 대부분의 종목에 대해 개인 공매도 기회를 확대하겠다는 얘기다.

금융위는 현재까지 대주 물량으로 2조~3조원가량을 확보했다고 밝혔다. 이는 공매도 금지 조치가 있기 전인 2019년 전체 대주 물량인 230억원을 크게 뛰어넘는 규모다.

기존 개인 물량(신용융자를 받아 매수한 주식 가운데 담보 제공에 동의한 물량)에 더해 증권사·보험사 등 기관 협조로 확보한 물량까지 개인 대주 풀에 활용하기로 했다.

원본보기

공매도 부분적 재개 관련 발표하는 금융위원장
(서울=연합뉴스) 은성수 금융위원장이 3일 서울 종로구 정부서울청사 합동브리핑실에서 공매도 부분적 재개 관련 내용을 발표하고 있다. 2021.2.3
[금융위원회 제공. 재판매 및 DB 금지] photo@yna.co.kr

다만 대주 물량이 확보됐다고 해서 개인들이 적극적으로 주식을 빌려 공매도에 나설지는 미지수다.

우선 개인 투자자가 주식을 빌리려면 최소 연 2.5%의 이자를 내야 한다.

개인 대주 시스템을 통합 운영하는 주체인 한국증권금융이 각 증권사에 적용하는 금리가 연 2.5%이기 때문이다.

한 증권사 관계자는 "증권사마다 다르긴 하지만 대주 수수료를 10만원으로 가정했을 때 증권금융이 관리 명목으로 3만원을 가져가고, 주식을 빌려준 고객에게 7만원을 이자로 주는 구조가 대부분"이라고 설명했다.

그러나 이 같은 대주 이율은 최대 4%까지 높아질 수 있다.

증권금융이 다양한 종목의 물량을 확보하기 위해 대주 이율을 연 2.5%와 연 4.0%로 이원화할 계획이기 때문이다.

증권금융 관계자는 "물량을 구하기 어려운 종목에 한해 연 4% 이율을 적용할 계획"이라며 "대여자에게 더 현실적인 이율을 제공함으로써 많은 종목 및 수량을 확보하려는 취지"라고 설명했다.

그러나 빌려주는 수수료율이 높아지면 빌리는 투자자가 내야 하는 수수료 부담도 함께 커지기 때문에 공매도 진입 장벽은 높아지는 결과를 낳을 수 있다.

이에 따라 주식을 빌려주는 사람에게 더 높은 수수료를 제공하겠다는 취지라면 증권금융 수수료를 조정해야 할 필요가 있다는 지적도 나온다.

한 증권업계 관계자는 "증권금융이 가져가는 수수료를 조정할 필요가 있다는 의견 등이 금융위에 전달된 상태"라고 분위기를 전했다.

짧은 대여 기간도 문제다.

개인투자자가 공매도를 위해 주식을 빌린 경우 60일간만 대여할 수 있어, 외국인·기관이 활용하는 대차 시장에 비해 상환 기간이 짧다는 지적을 받아왔다.

대주 수수료가 4%인 종목을 빌린 경우라면 두 달 내 주가가 이자 낼 만큼은 떨어져야 공매도로 인한 수익을 조금이라도 볼 수 있는 것이다.

원본보기

[연합뉴스TV 제공]

금융위는 상환 기간과 관련해 외국인·기관이 더 유리한 구조가 아니라고 설명하고 있다. 대차 시장에서는 빌려준 쪽이 중도 상환을 요청할 경우 차입자가 반드시 상환해야 하기 때문에 상환기간이 정해진 경우보다 차입자가 더 큰 부담을 진다는 것이다.

다만 금융위도 개인에게 적용되는 60일이란 기간이 너무 짧다는 지적에 상환기간을 늘리는 방안을 검토 중이다.

금융당국 관계자는 "상환 기간 연장을 검토하고 있는 건 사실인지만, 상환 기간을 늘릴 경우 '(대주 가능) 물량 잠김' 현상도 나타날 수 있다"며 "물량 분배와 관련된 문제라 추가적인 검토가 필요하다"고 말했다.

금융당국은 조만간 이러한 내용 등을 포함해 개인 공매도 개선 대책을 추가 발표한다

728x90
반응형

'NEOgram > Issue' 카테고리의 다른 글

2021-02-10 (마감 시황)  (0) 2021.02.10
현대차,'애플카' 협력 중단  (0) 2021.02.09
공매도  (0) 2021.02.06
박셀바이오 2021-01-04 (월)  (0) 2021.01.04
2021 투자  (0) 2021.01.04
:
Posted by 패치#노트
2021. 2. 6. 21:09

공매도 NEOgram/Issue2021. 2. 6. 21:09

728x90
반응형

공매도

사실 이 용어는 셀트리온헬스케어때문에 알게되었다.

주가가 오르지 못하는 이유로 예전에 서성진 회장이 인터뷰 하는 것을 봤었다.

 

그 공매도가 작년 코로나에 의한 주식시장의 타격등에 의해서 금지가 되고 올해 초에는 미국의 게임스탑으로 인해 개미들과 헷지하는 큰 형님들과 싸움으로 인해 엄청난 이슈가 되었다.

원래는 3월 초에 공매도를 재개 한다고 했었지만.. 5월부터 다시 하기로 했다.

지금은 일부 종목들만 공매도가 가능할 것이라고 한다.

개인에 대한 공매도..대주거래..를 한다는 이야기도 있다.

 

http://naver.me/GAMDkwE0

 

공매도

특정 종목의 주가가 하락할 것으로 예상되면 해당 주식을 보유하고 있지 않은 상태에서 주식을 빌려 매도 주문을 내는 투자 전략이다. 주로 초단기 매매차익을 노리는 데 사용되는 기법이다.

m.terms.naver.com

특정 종목의 주가가 하락할 것으로 예상되면 해당 주식을 보유하고 있지 않은 상태에서 주식을 빌려 매도 주문을 내는 투자 전략이다. 주로 초단기 매매차익을 노리는 데 사용되는 기법이다. 향후 주가가 떨어지면 해당 주식을 싼 값에 사 결제일 안에 주식대여자(보유자)에게 돌려주는 방법으로 시세차익을 챙긴다. 공매도는 주식시장에 유동성을 공급하는 반면 시장 질서를 교란시키고 불공정거래 수단으로 악용되기도 한다.

 

www.econovill.com/news/articleView.html?idxno=518065

 

[긴급점검! 공매도②] ‘개미’ 달래기 나선 정부…개선책은 ‘글쎄’ - 이코노믹리뷰

[이코노믹리뷰=정다희 기자] 개인투자자의 역량이 커진 만큼 제도 개선 요구도 거세지고 있다. 개인투자자가 공매도를 할지 안할지는 차후의 문제가 됐다. 개인투자자가 공평하게 접근할 수 있

www.econovill.com

 

4월 3일부터는 불법 공매도에 대한 처벌을 강화한 자본시장법이 적용

 

읽어볼만한 뉴스..

naver.me/5eGXHByQ

 

[논썰] 만국의 개미들은 왜 공매도에 분노하나

최근 전세계 증시를 달구는 핫이슈는 바로 ‘공매도와의 전쟁’입니다. 미국 뉴욕증시에 상장된 게임스톱을 둘러싼 개인투자가와 기관투자자 간의 치열한 매매 공방입니다. 국내에서도 개인투

n.news.naver.com

금융당국은 3일 모든 상장주식에 대한 공매도 금지 조처를 5월2일까지 다시 연장하기로 했습니다. 다만, 5월3일부터는 코스피200과 코스닥150 지수를 구성하는 350개 종목에 한해 공매도를 재개하기로 했습니다. 당국이 개인투자자들의 반발과 정치권의 연장 압박에 기존의 재개 입장에서 한발 물러서 절충안을 선택한 것

 

data.krx.co.kr/contents/MDC/MDI/mdiLoader/index.cmd?menuId=MDC0203

 

KRX 정보데이터시스템

증권·파생상품의 시장정보(Marketdata), 공매도정보, 투자분석정보(SMILE) 등 한국거래소의 정보데이터를 통합하여 제공 서비스

data.krx.co.kr

2021.02.06 토요일

KRX 한국거래소에서 퍼온 상위 종목

 

728x90
반응형

'NEOgram > Issue' 카테고리의 다른 글

현대차,'애플카' 협력 중단  (0) 2021.02.09
공매도+1  (0) 2021.02.07
박셀바이오 2021-01-04 (월)  (0) 2021.01.04
2021 투자  (0) 2021.01.04
How might President Donald Trump fare with COVID-19?  (0) 2020.10.03
:
Posted by 패치#노트
2021. 1. 24. 18:02

C# Datetime Programming/C#2021. 1. 24. 18:02

728x90
반응형

https://thedeveloperblog.com/datetime-performance

C# DateTime Performance Class

Home | Contact Us CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript C# DateTime Performance Class This C# performance class optimizes accesses to the DateTime.Now method. DateTime performance. A program uses DateTime.Now to frequen

thedeveloperblog.com

728x90
반응형

'Programming > C#' 카테고리의 다른 글

변수, 딕셔너리 등등 변수명은 영문으로!!!!  (0) 2021.04.13
:
Posted by 패치#노트
2021. 1. 19. 18:43

KRX 회원사별 어디갔니? Programming/Python2021. 1. 19. 18:43

728x90
반응형

매일 저녁 돌리던 KRX 크롤링...ㅠ.ㅠ 홈페이지가 개편이 되면서 원래 자료를 취합해오던 회원사별 메뉴가 없어졌다.

어디로 간거냐..

 

한참을 뒤지던중...

[출처] KRX 홈페이지

 

이젠 데이터상품으로 데이터 장사를...........

내가 주식시장에 가져다준 돈이 얼마인데...ㅠ.ㅠ

 

이런것도..맘대로.. 못 보공. 흥.칫.뿡

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

* 셀트리온 코로나19 항체치료제, 이달 13일 임상 2상 결과 공개

 

셀트리온 코로나19 항체치료제, 이달 13일 임상 2상 결과 공개 | 연합뉴스

셀트리온 코로나19 항체치료제, 이달 13일 임상 2상 결과 공개, 김잔디기자, 산업뉴스 (송고시간 2021-01-05 06:03)

www.yna.co.kr

셀트리온[068270]의 신종 코로나바이러스 감염증(코로나19) 항체치료제 '렉키로나주'(성분명 레그단비맙·코드명 CT-P59)의 임상 2상 시험 결과가 이달 13일 최초 공개된다.

5일 제약·바이오 업계에 따르면 셀트리온은 이달 13일 대한약학회가 주최하는 2021 하이원신약개발심포지아에 참여해 렉키로나주의 글로벌 임상 2상 결과를 발표하기로 했다.

728x90
반응형

'Recycle' 카테고리의 다른 글

SK바이오사이언스  (0) 2021.02.12
SK바이오사이언스 상장 추진  (0) 2021.02.07
공매도 재개-3월16일  (0) 2021.01.02
셀트리온-서성진 회장  (0) 2021.01.01
엔케이맥스, 알츠하이머 임상1상 투약일정 확정  (0) 2020.12.23
:
Posted by 패치#노트
2021. 1. 4. 22:51

박셀바이오 2021-01-04 (월) NEOgram/Issue2021. 1. 4. 22:51

728x90
반응형

면역세포치료제 기업으로 향후 성장 기대감 지속에 상한가

728x90
반응형

'NEOgram > Issue' 카테고리의 다른 글

공매도+1  (0) 2021.02.07
공매도  (0) 2021.02.06
2021 투자  (0) 2021.01.04
How might President Donald Trump fare with COVID-19?  (0) 2020.10.03
도쿄증권거래소  (0) 2020.10.01
:
Posted by 패치#노트
2021. 1. 4. 08:42

2021 투자 NEOgram/Issue2021. 1. 4. 08:42

728x90
반응형

http://naver.me/xyUOU5HV

올해 디지털뉴딜·탄소중립 등 R&D에 5.8조원 투자한다

(자료=과학기술정보통신부 제공) [이데일리 이후섭 기자] 과학기술정보통신부는 내년 총 5조 8161억원을 투자해 기초연구 지원, 디지털뉴딜 가속화, 탄소중립 실현 등 연구개발(R&D)을 추진할 계획

n.news.naver.com

과기정통부, `과학기술·ICT 분야 연구개발사업 종합시행계획`
기초연구사업 예산 1조8029억원…전년대비 2917억원 확대
6G·자율주행·PIM반도체·블록체인 등 신기술 개발에 727억 투입
탄소중립 등 기후변화 대응에 1591억, 바이오 개발에도 5336억


과기정통부는 총 5조8161억원을 투자하는 `2021년도 과학기술·정보통신방송(ICT) 분야 연구개발사업 종합시행계획`을 확정하고, 본격적으로 사업을 추진한다고 3일 밝혔다. 이번 종합시행계획은 과기정통부 전체 R&D 예산 총 8조8682억원 중에서 국가과학기술연구회, 직할출연기관 연구운영비 등을 제외한 과학기술분야 4조6061억원, ICT 분야 1조2100억원을 대상으로 하며 △기초연구(1조8029억원) △원천연구(2조8459억원) △R&D 사업화(3415억원) △인력양성(2509억원) △R&D 기반조성(5749억원) 등을 포함

728x90
반응형

'NEOgram > Issue' 카테고리의 다른 글

공매도  (0) 2021.02.06
박셀바이오 2021-01-04 (월)  (0) 2021.01.04
How might President Donald Trump fare with COVID-19?  (0) 2020.10.03
도쿄증권거래소  (0) 2020.10.01
KG그룹  (0) 2020.09.24
:
Posted by 패치#노트
2021. 1. 2. 22:58

공매도 재개-3월16일 Recycle2021. 1. 2. 22:58

728x90
반응형

http://naver.me/5y4v55Hl

[2021 증시 진단] "공매도 재개시 단기조정 불가피… 바이오株 타격"

(서울=뉴스1) 박응진 기자,정은지 기자,권혜정 기자,전민 기자 = 국내 주요 증권사 리서치센터장들은 오는 3월16일에 공매도(空賣渡) 거래가 재개되면 증시의 단기 조정이 불가피하다고 내다봤다.

n.news.naver.com

국내 주요 증권사 리서치센터장들은 오는 3월16일에 공매도(空賣渡) 거래가 재개되면 증시의 단기 조정이 불가피하다고 내다봤다. 코로나19발 폭락장 이후 국내 증시가 V자 반등하며 사상 최고 행진을 거듭한 가운데 지난 1년 동안 금지된 공매도 거래가 한꺼번에 몰려 하락장이 펼쳐질 수 있다는 것이다. 특히 바이오주의 타격이 클 것으로 전망됐다. 다만 개인투자자들의 적극적인 주식 투자 참여로 인해 공매도 재개에 따른 조정폭이 그렇게 크지는 않을 것이라는 의견도 제기됐다.

대신증권에 따르면 과거에도 공매도 거래를 재개한 이후 코스피 지수는 단기 조정을 겪었다. 2009년 5월29일 공매도 재개 이후 코스피는 6월 한 달 동안 고점 대비 -3% 수준에서 기간 조정을 거쳤다. 또 2011년 11월9일 공매도 거래 재개 이후 코스피는 1770~1920p(고점 대비 7.8% 가격 조정)에서 등락했다. 다만 각각 조정 후 상승추세를 재개했다.

앞서 공매도 금지 직전 코스닥 시장에서 공매도 잔고가 많이 쌓인 종목은 신라젠, 국일제지, CMG제약, 에이치엘비, 셀트리온헬스케어 등 제약·바이오주가 대부분이었다. 이에 따라 공매도 거래가 재개됐을 때 이들 제약·바이오주 주가의 타격이 특히 클 수 있다.

728x90
반응형
:
Posted by 패치#노트
2021. 1. 1. 22:22

셀트리온-서성진 회장 Recycle2021. 1. 1. 22:22

728x90
반응형

http://naver.me/GQ4XxUoa

[단독]은퇴 약속 지킨 서정진 “원격진료 스타트업 맨땅서 시작”

서정진 셀트리온 회장(63)이 31일 회장직에서 물러났다. ‘다른 임원과 마찬가지로 65세 정년(한국 나이)에 떠나겠다’던 은퇴 약속을 지킨 것이다. 서 회장이 5000만 원으로 창업한 셀트리온의 상

n.news.naver.com

새해에 인공지능(AI) 원격진료 스타트업을 맨땅에서 시작할 계획”이라고 말했다. 직접 병원을 찾기 힘든 고령자가 집에서 채취한 소량의 혈액만으로 원격진료를 받을 수 있도록 한다는 것이 서 회장의 구상

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

http://m.newspim.com/news/view/20201222000081

엔케이맥스, 알츠하이머 임상1상 투약일정 확정

[서울=뉴스핌] 김세원 기자 = 엔케이맥스는 알츠하이머 환자 대상 임상 1상의 투약일정을 22일 공개했다. 엔케이맥스는 슈퍼NK 자가 면역세포치료제(SNK01) 10억개 투여 대상자 3명의 첫 투약 일정

m.newspim.com

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

패스트캠퍼스

[파이썬을 활용한 데이터 전처리 Level UP]

챌린지 참여 후기

 

마지막 실전 프로젝트를 정리하기전 이번 챌린지 이벤트 참여에 대한 소회..

 

나에게 아직은 데이터분석은 생소한 분야임에는 틀림이 없다. 하지만 한단계 레벨업을 하기 위해서는 반드시 필요하다가 나 스스로가 깨닫고 있다.

수 많은 용어들과 통계학, 라이브러리 등 적응이 잘 안 되고 있지만 반복적인 학습을 통해서 매일매일 해나가도 보면 언젠가는 도달 할 수 있지 않을까?

아직도 늦었다고 생각하는가?

오늘도 한 걸음만 더 나아가보자!!!

할 수 있다!!!!!

해야만 한다!!!!!


 

01. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 01. (1) 문제 소개

* 대회 소개

- 출처 : 삼성 신용카드 매출 예측 경진대회

 . 문제 제공자 : FUNDA (데이콘)

 . 소상공인 가맹점 신용카드 빅데이터와 AI로 매출 예측 분석 

dacon.io/competitions/official/140472/overview/

 

상점 신용카드 매출 예측 경진대회

출처 : DACON - Data Science Competition

dacon.io

// 하나의 레코드가 하나로 대응 되는 거라고 생각하면 된다.

 

02. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 02-1. (2) 학습 데이터 구축 (이론)

* 기본 데이터 구조 설계

 - 레코드가 수집된 시간 기준으로 3개월 이후의 총 매출을 예측하도록 구조를 설계해야 한다.

 - 시점은 월단위로 정의

 

* 시점변수 생성

// 시점 변수 생성이 필요하다.

 - 시점 변수 생성 : 시점 (t) = (연도 - 2016 ) * 12 + 월

 

* 변주 변수 탐색

// 부적절하다고 하는 것은 데이터 기반이 아니라고 생각하면 된다.

// 범주형 변수로 상태 공간이 매우 커서, 더미화하기에는 부적절하다고 판단했다.

// 결측은 제거하지 않고 없음이라고 변환한다.

 

* 학습 데이터 구조 작성

// 정리되지 않은 데이터를 바탕으로 학습 데이터를 생성해야 하는 경우에는 레코드의 단위를 고려하여 학습 데이터의 구조를 먼저 작성하는 것이 바람직하다.

// 중복을 제거

 

* 평균 할부율 부착

// 할부를 많이 하는 그룹이 있을 것 같아서 groupby 를 이용해서 생성 replace 를 이용해서 다시 만들었고

 

* 기존 데이터에 부착 테크닉

// concat, merge 를 이용하면 일반적인 것은 붙일 수 있는데

// 다른 데이터에서 붙여야 하므로 case1 t가 유니크한 경우, 각 데이터를 정렬 후, 한 데이터에 대해 shift 를 사용

// case 2. t 가 유니크하지 않은 경우, t_1 변수를 생성

 

* 기존 데이터 부착 테크닉 Case 1

// shift 를 이용해서 concat 수행

// df2.shift(1)

// 시계열 예측에서 많이 쓰이는 패턴이다.

 

* 기존 데이터 부착 테크닉 Case 2

// 새로운 컬럼은 생성하서 merge를 수행한다.

 

* 기존 매출 합계 부착

 

* 기존 지역별 매출 합계 부착

 

* 라벨 부착하기

// 라벨의 경우에는 어떤 시점 t 에 상점 id 별로 붙이고 1 2 3 에 대해서 더 해준다.

 

03. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 02-2. (2) 학습 데이터 구축 (실습)

 

// region 에 결측이 있지만 대체를 하기에는 힘들고 제거를 하기에는 힘들다. 그래서 없음으로 표시

// 변수 목록 탐색을 통해서 상점 ID 가 일치 하는지 탐색을 해야 한다.

 

* 학습 데이터 구축

// 일자에서 연, 월, 일을 구분 해야 하므로 split 을 사용해서 구분

// 데이터 병합을 위한 새로운 컬럼 생성 및 기존 시간 변수를 삭제한다.

 

* 불필요한 변수 제거

// card_id, card_company는 특징으로 사용하기에는 너무 세분화 될수 있어서, 특징으로 유요할 가능성이 없다고 삭제.

// 주관적인 판단으로 처리한 것이다.

 

* 업종 특성, 지역, 할부 평균 탐색

// 대부분이 일시불이므로, installment_term 변수를 할부인지 아닌지 여부로 변환해야 한다.

// astype(int) 로 해서 할부는 0 , 할부하지 않은 것은 1로 나타난다.

 

// 상점별 평균 할부 비율

// .mean( ) 함수를 통해서 각 평균을 구해서 store_id 를 본다.

 

// 지역은 region 제거를 할수 없기 때문에 없음으로 대체 '없음'

// 업종도 비슷하다.

 

// 피벗 테이블을 생성하고 결측을 바로 앞 값으로 채울 수 있다.

// 값이 없는 경우는 결측으로 출력이 나옴.

// ffill 바로 앞 값과 bfill 그 다음은 바로 뒤값으로 채워준다.

 

// 변수 실수를 줄여야 한다.

// 모델 학습을 적용하기 위한 일반적인 전처리에 대한 준비를 했다.

 

04. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 03. (3) 학습 데이터 탐색 및 전처리

* 학습 데이터 기초 탐색 및 전처리

 - 특징과 라벨 분리

// 필요없는 라벨들은 drop 으로 제거 해준다. axis = 1

 

 - 학습데이터와 평가 데이터로 데이터 분할

// 특징 대비 샘플이 많다는 것을 알 수 있다. 37673

// 회귀 문제 예측 문제라고 예상하면 된다.

 

 - 이상치 제거

// IQR rule 을 위배하지 않는 bool list 계산 (True : 이상치 없음, False : 이상치 있음)

// Y_condition 이상치가 아닌 값들로 구성된것

 

 - 치우침 제거

// 모두 좌로 치우침을 확인 할수가 있다.

// 왜도의 절대값이 1.5이상인 컬럼만 가져왔다.

// Train_X.skew().abs() > 1.5

 

// 스케일링 수행

sklearn.preprocessing MinMaxScaler 수행

 

// 원래는 데이터 프레임을 정의하는 것이 좋기는 한데 메모리 문제로 처음부터 정의하지 않음

// 아무리 꼼꼼하더라도 모든 변수를 제거 할 필요는 없다.

 

// abs( ) Documentation

docs.python.org/3/library/functions.html#abs

abs(x)

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

 

3. Data model — Python 3.9.1rc1 documentation

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define

docs.python.org

object.__abs__(self)

 

 

05. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 04. (4) 모델 학습

// 모델 선택

// 샘플 대비 특징이 적고, 특징의 타입이 전부연속형으로 같다.

// kNN, RandomForestRegressor, LightGBM 고려함.

// 신경망을 쓰기에는 변수가 적기 때문에 좋은 결과를 기대하기는 어렵다.

 

// sklearn.ensemble.RandomForestRegressor Documentation

scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html

class sklearn.ensemble.RandomForestRegressor(n_estimators=100, *, criterion='mse', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None)

A random forest regressor.

A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the max_samples parameter if bootstrap=True (default), otherwise the whole dataset is used to build each tree.

Read more in the User Guide.

 

Parameters

n_estimatorsint, default=100

The number of trees in the forest.

Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22.

criterion{“mse”, “mae”}, default=”mse”

The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion, and “mae” for the mean absolute error.

New in version 0.18: Mean Absolute Error (MAE) criterion.

max_depthint, default=None

The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.

min_samples_splitint or float, default=2

The minimum number of samples required to split an internal node:

  • If int, then consider min_samples_split as the minimum number.

  • If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split.

Changed in version 0.18: Added float values for fractions.

min_samples_leafint or float, default=1

The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.

  • If int, then consider min_samples_leaf as the minimum number.

  • If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node.

Changed in version 0.18: Added float values for fractions.

min_weight_fraction_leaffloat, default=0.0

The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.

max_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto”

The number of features to consider when looking for the best split:

  • If int, then consider max_features features at each split.

  • If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split.

  • If “auto”, then max_features=n_features.

  • If “sqrt”, then max_features=sqrt(n_features).

  • If “log2”, then max_features=log2(n_features).

  • If None, then max_features=n_features.

Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.

max_leaf_nodesint, default=None

Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.

min_impurity_decreasefloat, default=0.0

A node will be split if this split induces a decrease of the impurity greater than or equal to this value.

The weighted impurity decrease equation is the following:

N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)

where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child.

N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed.

New in version 0.19.

min_impurity_splitfloat, default=None

Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf.

Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 0.25. Use min_impurity_decrease instead.

bootstrapbool, default=True

Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.

oob_scorebool, default=False

whether to use out-of-bag samples to estimate the R^2 on unseen data.

n_jobsint, default=None

The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

random_stateint or RandomState, default=None

Controls both the randomness of the bootstrapping of the samples used when building trees (if bootstrap=True) and the sampling of the features to consider when looking for the best split at each node (if max_features < n_features). See Glossary for details.

verboseint, default=0

Controls the verbosity when fitting and predicting.

warm_startbool, default=False

When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See the Glossary.

ccp_alphanon-negative float, default=0.0

Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.

New in version 0.22.

max_samplesint or float, default=None

If bootstrap is True, the number of samples to draw from X to train each base estimator.

  • If None (default), then draw X.shape[0] samples.

  • If int, then draw max_samples samples.

  • If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1).

New in version 0.22.

 

Attributes

base_estimator_DecisionTreeRegressor

The child estimator template used to create the collection of fitted sub-estimators.

estimators_list of DecisionTreeRegressor

The collection of fitted sub-estimators.

feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.

n_features_int

The number of features when fit is performed.

n_outputs_int

The number of outputs when fit is performed.

oob_score_float

Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.

oob_prediction_ndarray of shape (n_samples,)

Prediction computed with out-of-bag estimate on the training set. This attribute exists only when oob_score is True.

 

 

// 파라미터 그리드를 생성하고 하이퍼 마라미터 그리드를 parma_dict 에 추가함.

 

// sklearn.metrics.mean_absolute_error Documentation

scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html

sklearn.metrics.mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')

Mean absolute error regression loss

Read more in the User Guide.

 

Parameters

y_truearray-like of shape (n_samples,) or (n_samples, n_outputs)

Ground truth (correct) target values.

y_predarray-like of shape (n_samples,) or (n_samples, n_outputs)

Estimated target values.

sample_weightarray-like of shape (n_samples,), optional

Sample weights.

multioutputstring in [‘raw_values’, ‘uniform_average’] or array-like of shape (n_outputs)

Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

‘raw_values’ :

Returns a full set of errors in case of multioutput input.

‘uniform_average’ :

Errors of all outputs are averaged with uniform weight.

 

Returns

lossfloat or ndarray of floats

If multioutput is ‘raw_values’, then mean absolute error is returned for each output separately. If multioutput is ‘uniform_average’ or an ndarray of weights, then the weighted average of all output errors is returned.

MAE output is non-negative floating point. The best value is 0.0.

 

// 값이 작을 수록 좋기 때문에 초기 값은 매우 큰 값으로 정의함.

// LightGBM 에서 DataFrame 이 잘 처리 되지 않는 것을 방지하기 위해서 .values 를 사용하였다.

 

06. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 05. (5) 모델 적용

// 모델 학습이 다 끝나서 새로 들어온 데이터에서 대해서 예측을 해보는 것이다.

// pipeline 을 이용해서 구축할 수 있다.

 

 

07. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 01. (1) 문제 소개

 

* 아파트 실거래가 예측

 

// 실제 데이터는 크기가 크기 때문에 샘플 데이터로 주었다.

// 참조 데이터는 대회 문제 해결을 위해, 강사가 직접 수집한 데이터이며, 어떠한 정제도 하지 않았다.

 

08. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 02. (2) 변수 변환 및 부착

 

* 변수 부착시에 자주 발생하는 이슈 및 해결 방안

// 데이터 크기가 줄어도는 경우가 존재한다.

// np.isin 함수 사용

 

// numpy.isin Documentation

numpy.org/doc/stable/reference/generated/numpy.isin.html

numpy.isin(element, test_elements, assume_unique=False, invert=False)

Calculates element in test_elements, broadcasting over element only. Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise.

 

Parameters

elementarray_like

Input array.

test_elementsarray_like

The values against which to test each value of element. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters.

assume_uniquebool, optional

If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

invertbool, optional

If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False. np.isin(a, b, invert=True) is equivalent to (but faster than) np.invert(np.isin(a, b)).

 

Returns

isinndarray, bool

Has the same shape as element. The values element[isin] are in test_elements.

 

* 불필요한 변수 제거

// 사용하지 않는 변수들은 미리 삭제하여 메모리 부담을 줄여준다.

 

* 범주 변수 구간화 : floor 변수

// floor 변수는 이론적으로는 연속형 변수지만, 범주형 변수로 간주하는 것이 적절하다.

// 너무 정교하게 하면 과최적화가 일어날 수가 있다.

// 박스플롯을 그려서 군집을 세분화한다.

 

* 시세 변수 추가

// groypby를 이용, 구별 전체 평균 시세 변수 추가

// 구별 작년 평균 시세, 구별 작년 거래량 변수 추가

// 아파트별 평균가격 변수 추가

 

* 실습

// engine = 'python' 에러를 줄이기 위해

 

// 일치하지 않는 경우를 확인해야 한다.

 

// isin 함수를 통해서 확인

// df_loc 가 ref_df_loc에 포함되지 않는 경우가 다수 있음을 확인했다.

 

// 시도와 법정동이 완전히 똑같은 행이 있어 제거를 하고, dong 에 리가 붙어 있으면 제거 해야 한다.

 

// apartment_id 를 삭제 할려고 했으나 완전히 유니크하지 않으므로 어느정도 사용이 가능할 것이라 보여서 살펴뒀음.

 

09. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 03. (3) 외부 데이터 부착

// 공원 데이터를 추가 한다.

// 동별로 유형에 공원수를 계산한 뒤, 데이터를 부착한다.

 

// 어린이집 데이터를 추가

// 처리에 관한 방법은 비슷하지만 어떤식으로 정리를 해야 할지는 많은 경험치가 필요할 듯 보인다.

 

10. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 04. (4) 모델 학습

* 데이터 분리

// 라벨 변수 할당

// 불필요한 변수를 제거하여 정의

// 학습 데이터의 크기가(27012, 22) 임을 확인, 특징 22개 데이터의 크기는 27012 이다.

 

// 더미화

// 샘플 대비 특징이 많지 않고, 범주형 변수의 개수도 많지 않아 더미화를 하더라도 큰 문제가 없다고 판단

 

* 결측 대체

// 원 데이터에는 결측이 없으나, 과거 거래와 관련돈 변수를 부착하는 과정에서 과거가 없는 데이터에 대한 결측이 생성된다.

 

* 모델 재학습

// 학습 데이터와 평가 데이터를 부착하고, 재학습을 실시함.

// 시간이 허락되면 해주는 것이 바람직하다.

 

* 실습

// 샘플 대비 특징이 매우 적다는 것은 더미화 가능하다

// 샘플이 충분히 많이 있으므로 트리 뿐만 아니라 트리 기반의 앙상블도 적절함.

 

* 더미화시킴

 

* 변수 부착 과정에서 생성된 결측 대체

 

// key 가 모델 function

 

// sklearn.metrics.mean_absolute_error 를 사용함.

 

// LGB 은 아스키 코드가 포함되면 작동안하는 경우가 있기 때문에 ndarrary 로 작업을 한다.

 

11. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 05. (5) 모델 적용

 

* 파이프라인 구축

// 새로들어온 데이터의 아파트 값 예측

// 파이프라인 사용에 필요한 모든 요소를 pickle 을 사용하였음

 

// pckl 로 저장함.

// pickle.dump

// pickle 의 파일들은 binary 로 수행한다.

 

// pickle Documentation

docs.python.org/3/library/pickle.html

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” 1 or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

 

Comparison with json

There are fundamental differences between the pickle protocols and JSON (JavaScript Object Notation):

  • JSON is a text serialization format (it outputs unicode text, although most of the time it is then encoded to utf-8), while pickle is a binary serialization format;

  • JSON is human-readable, while pickle is not;

  • JSON is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific;

  • JSON, by default, can only represent a subset of the Python built-in types, and no custom classes; pickle can represent an extremely large number of Python types (many of them automatically, by clever usage of Python’s introspection facilities; complex cases can be tackled by implementing specific object APIs);

  • Unlike pickle, deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability.

// 솔직히 난 json 타입을 더 선호하기는 하던데..

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 28 회차 미션 시작]

 

* 복습

 - 마지막 미션!!!!

 - 범주형 변수 문자에 대한 처리 방법

 - 이상치 제거.. 그리고 스케일링

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 01. 문제 정의 및 탐색 방법]

 

 

* 문제 정의

// 하나의 값에 치우친 데이터로 편향되는 문제

// 클래스 불균형 문제가 있는 모델은 정확도가 높고, 재현율이 매우 낮은 경향이 있다.

 

 

* 용어 정의

// 다수 클래스 : 대부분 샘플이 속한 클래스

// 소수 클래스 : 대부분 샘플이 속하지 않은 클래스

 

* 발생 원인

 

 

 

* 탐색 방법 (1) 클래스 불균형 비율

 

 

// 9 이상이면 편향된 모델이 학습될 가능성이 있다.

 

 

 

* 탐색 방법 (2) k- 최근접 이웃을 활용하는 방법

 

 

// k 값은 5~ 11 정도.. 보통은 11정도를 선호하는 수치이다.

 

* 문제 해결의 기본 아이디어

 

 

// 소수 클래스에 대한 결정 공간을 넓히는 것이다.

 


 

[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 02-1. 재샘플링 - 오버샘플링과 언더 샘플링(이론)]

 

 

 

* 분류 : 오버샘플링과 언더샘플링

 

 

 

* 어디에 만들고 어느 것을 지울까?

// 결정 경계에 가까운 다수 클래스 샘플을 제거하고, 결정 경계에 가까운 소수 클래스 샘플을 생성해야 한다.

 

 

// 평가 데이터에 대해서는 절대로 재샘플링을 적용하면 안된다!!!!

 

* 대표적인 오버샘플링 알고리즘 : SMOTE

 

 

 

 

* imblearn.over_sampling.SMOTE Documentation

imbalanced-learn.org/stable/generated/imblearn.over_sampling.SMOTE.html

classimblearn.over_sampling.SMOTE(*, sampling_strategy='auto', random_state=None, k_neighbors=5, n_jobs=None)[source]

Class to perform over-sampling using SMOTE.

This object is an implementation of SMOTE - Synthetic Minority Over-sampling Technique as presented in [1].

Read more in the User Guide.

 

Parameters

sampling_strategyfloat, str, dict or callable, default=’auto’

Sampling information to resample the data set.

  • When float, it corresponds to the desired ratio of the number of samples in the minority class over the number of samples in the majority class after resampling. Therefore, the ratio is expressed as 

     where 

     is the number of samples in the minority class after resampling and 

     is the number of samples in the majority class.

    Warning

    float is only available for binary classification. An error is raised for multi-class classification.

  • When str, specify the class targeted by the resampling. The number of samples in the different classes will be equalized. Possible choices are:

    'minority': resample only the minority class;

    'not minority': resample all classes but the minority class;

    'not majority': resample all classes but the majority class;

    'all': resample all classes;

    'auto': equivalent to 'not majority'.

  • When dict, the keys correspond to the targeted classes. The values correspond to the desired number of samples for each targeted class.

  • When callable, function taking y and returns a dict. The keys correspond to the targeted classes. The values correspond to the desired number of samples for each class.

random_stateint, RandomState instance, default=None

Control the randomization of the algorithm.

  • If int, random_state is the seed used by the random number generator;

  • If RandomState instance, random_state is the random number generator;

  • If None, the random number generator is the RandomState instance used by np.random.

k_neighborsint or object, default=5

If int, number of nearest neighbours to used to construct synthetic samples. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_jobsint, default=None

Number of CPU cores used during the cross-validation loop. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 

* 대표적인 언더샘플링 알고리즘 : NearMiss

// 평균 거리가 짧은 다수 클래스 샘플을 순서대로 제거하는 방법이다.

 

 

// version 2 소수 클래스 샘플까지의 평균 거리를 사용한다.

 

* imblearn.under_sampling.NearMiss Documentation

imbalanced-learn.org/stable/generated/imblearn.under_sampling.NearMiss.html

classimblearn.under_sampling.NearMiss(*, sampling_strategy='auto', version=1, n_neighbors=3, n_neighbors_ver3=3, n_jobs=None)[source]

Class to perform under-sampling based on NearMiss methods.

Read more in the User Guide.

 

Parameters

sampling_strategyfloat, str, dict, callable, default=’auto’

Sampling information to sample the data set.

  • When float, it corresponds to the desired ratio of the number of samples in the minority class over the number of samples in the majority class after resampling. Therefore, the ratio is expressed as 

     where 

     is the number of samples in the minority class and 

     is the number of samples in the majority class after resampling.

    Warning

    float is only available for binary classification. An error is raised for multi-class classification.

  • When str, specify the class targeted by the resampling. The number of samples in the different classes will be equalized. Possible choices are:

    'majority': resample only the majority class;

    'not minority': resample all classes but the minority class;

    'not majority': resample all classes but the majority class;

    'all': resample all classes;

    'auto': equivalent to 'not minority'.

  • When dict, the keys correspond to the targeted classes. The values correspond to the desired number of samples for each targeted class.

  • When callable, function taking y and returns a dict. The keys correspond to the targeted classes. The values correspond to the desired number of samples for each class.

versionint, default=1

Version of the NearMiss to use. Possible values are 1, 2 or 3.

n_neighborsint or object, default=3

If int, size of the neighbourhood to consider to compute the average distance to the minority point samples. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_neighbors_ver3int or object, default=3

If int, NearMiss-3 algorithm start by a phase of re-sampling. This parameter correspond to the number of neighbours selected create the subset in which the selection will be performed. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_jobsint, default=None

Number of CPU cores used during the cross-validation loop. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 02-2. 재샘플링 - 오버샘플링과 언더 샘플링(실습)]

 

 

// kNN 을 사용해서 클래스 불균형도 테스트를 해준다.

// KNeighborsClassifier

// 재현율 0% 로 불균형이 심각한 수준이라 볼 수 있다.

 

 

 

 

 

 

[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 03-1 비용 민감 모델 (이론)]

 

 

// 모델의 학습 변경한 모델이라고 볼 수 있다. 전처리라고 보기는 좀 어렵다.

 

* 정의

// 비용을 위양성 비용보다 크게 설정

 

 

 

* 확률 모델

 

 

 

* 관련문법: .predict_proba

 

 

 

* Tip.Numpy 와 Pandas 잘 쓰는 기본 원칙 : 가능하면 배열 단위 연산을 하라

// 유니버설 함수, 브로드캐스팅, 마스크 연산을 최대한 활용

 

 

 

* 비확률 모델 (1) 서포트 벡터 머신

 

 

 

* 비확률 모델 (2) 의사결정 나무

 

 

 

* 관련문법 : class_weight

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 03-2 비용 민감 모델 (실습)]

 

* 실습

// kNN 을 사용한 클래스 불균형 테스트들을 사용

 

 

// cost_sensitive_model 의 함수를 만들어 준다.

 

// 둔감하다는 표현이 더 좋은 표현이라고 생각하면 된다.

 

 

 

// class weight 도 튜닝을 해야 한다고 보면 된다.

 

// sklearn.svm.SVC Documentation

scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)

C-Support Vector Classification.

The implementation is based on libsvm. The fit time scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples. For large datasets consider using sklearn.svm.LinearSVC or sklearn.linear_model.SGDClassifier instead, possibly after a sklearn.kernel_approximation.Nystroem transformer.

The multiclass support is handled according to a one-vs-one scheme.

For details on the precise mathematical formulation of the provided kernel functions and how gamma, coef0 and degree affect each other, see the corresponding section in the narrative documentation: Kernel functions.

Read more in the User Guide.

 

Parameters

Cfloat, default=1.0

Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.

kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’

Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).

degreeint, default=3

Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.

gamma{‘scale’, ‘auto’} or float, default=’scale’

Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’.

  • if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma,

  • if ‘auto’, uses 1 / n_features.

Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.

coef0float, default=0.0

Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.

shrinkingbool, default=True

Whether to use the shrinking heuristic. See the User Guide.

probabilitybool, default=False

Whether to enable probability estimates. This must be enabled prior to calling fit, will slow down that method as it internally uses 5-fold cross-validation, and predict_proba may be inconsistent with predict. Read more in the User Guide.

tolfloat, default=1e-3

Tolerance for stopping criterion.

cache_sizefloat, default=200

Specify the size of the kernel cache (in MB).

class_weightdict or ‘balanced’, default=None

Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))

verbosebool, default=False

Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.

max_iterint, default=-1

Hard limit on iterations within solver, or -1 for no limit.

decision_function_shape{‘ovo’, ‘ovr’}, default=’ovr’

Whether to return a one-vs-rest (‘ovr’) decision function of shape (n_samples, n_classes) as all other classifiers, or the original one-vs-one (‘ovo’) decision function of libsvm which has shape (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one (‘ovo’) is always used as multi-class strategy. The parameter is ignored for binary classification.

Changed in version 0.19: decision_function_shape is ‘ovr’ by default.

New in version 0.17: decision_function_shape=’ovr’ is recommended.

Changed in version 0.17: Deprecated decision_function_shape=’ovo’ and None.

break_tiesbool, default=False

If true, decision_function_shape='ovr', and number of classes > 2, predict will break ties according to the confidence values of decision_function; otherwise the first class among the tied classes is returned. Please note that breaking ties comes at a relatively high computational cost compared to a simple predict.

New in version 0.22.

random_stateint or RandomState instance, default=None

Controls the pseudo random number generation for shuffling the data for probability estimates. Ignored when probability is False. Pass an int for reproducible output across multiple function calls. See Glossary.

 

Attributes

support_ndarray of shape (n_SV,)

Indices of support vectors.

support_vectors_ndarray of shape (n_SV, n_features)

Support vectors.

n_support_ndarray of shape (n_class,), dtype=int32

Number of support vectors for each class.

dual_coef_ndarray of shape (n_class-1, n_SV)

Dual coefficients of the support vector in the decision function (see Mathematical formulation), multiplied by their targets. For multiclass, coefficient for all 1-vs-1 classifiers. The layout of the coefficients in the multiclass case is somewhat non-trivial. See the multi-class section of the User Guide for details.

coef_ndarray of shape (n_class * (n_class-1) / 2, n_features)

Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel.

coef_ is a readonly property derived from dual_coef_ and support_vectors_.

intercept_ndarray of shape (n_class * (n_class-1) / 2,)

Constants in decision function.

fit_status_int

0 if correctly fitted, 1 otherwise (will raise warning)

classes_ndarray of shape (n_classes,)

The classes labels.

probA_ndarray of shape (n_class * (n_class-1) / 2)probB_ndarray of shape (n_class * (n_class-1) / 2)

If probability=True, it corresponds to the parameters learned in Platt scaling to produce probability estimates from decision values. If probability=False, it’s an empty array. Platt scaling uses the logistic function 1 / (1 + exp(decision_value * probA_ + probB_)) where probA_ and probB_ are learned from the dataset [2]. For more information on the multiclass case and training procedure see section 8 of [1].

class_weight_ndarray of shape (n_class,)

Multipliers of parameter C for each class. Computed based on the class_weight parameter.

shape_fit_tuple of int of shape (n_dimensions_of_X,)

Array dimensions of training vector X.

 

Methods

decision_function(X)

Evaluates the decision function for the samples in X.

fit(X, y[, sample_weight])

Fit the SVM model according to the given training data.

get_params([deep])

Get parameters for this estimator.

predict(X)

Perform classification on samples in X.

score(X, y[, sample_weight])

Return the mean accuracy on the given test data and labels.

set_params(**params)

Set the parameters of this estimator.

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 각 불균형 문제에 대해서 샘플링 및 비용 민감 모델을 어떻게 다룰 것인지에 대해서 학습했다.

 

 

 

https://bit.ly/3m7bW22

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 27 회차 미션 시작]

 

* 복습

 - sklearn.impute.SimpleImputer, fillna를 이용해서 ffill, bfill  처리

 - 결측치 예측 모델 활용 방법

 



[04. Part 4) Ch 18. 문자보다는 숫자 범주형 변수 문제 - 01. 문제 정의 및 해결 방법]

* 문제 정의

 - 데이터에 범주형 변수가 포함되어 있어, 대다수의 지도 학습 모델이 학습되지 않거나 비정상적으로 학습되는 문제를 의미

  . str 타입의 범주형 변수가 포함되면 대다수의 지도 학습 모델 자체가 학습이 되지 않음

  . int 혹은 float 타입의 범주형 변수는 모델 학습은 되나, 비정상적으로 학습이 되지만, 입문자는 이를 놓치는 경우가 종종있다.

 

 - 모델 학습을 위해 범주형 변수는 반드시 숫자로 변환되어야 하지만, 임의로 설정하는 것은 매우 부적절하다.

  . (예시) 종교 변수 : 기독교 = 1, 불교 = 2, 천주교 =3

   불교는 기독교의 2배라는 등의 대수 관계가 실제로 존재하지 않지만, 이처럼 변환하면 비상적인 관계가 생성된다.

// 적절한 숫자로 변화 되어야 한다.

 

 - 특히, 코드화된 범주형 변수도 적절한 숫자로 변환해줘야 한다.

 

* 범주형 변수 판별

 - 범주형 변수는 상태 공간의 크기가 유한한 변수를 의미하며, 반드시 모데인이나 변수의 상태 공간을 바탕으로 판단해야 한다.

 

 - int 혹은 float 타입으로 정의된 변수는 반드시 연속형 변수가 아닐 수 있다는 점에 주의해야 한다.

 

 - (예시) 월(month)은 비록 숫자지만 범주형 변수이다.

 

* 범주형 변수 변환 방법 (1) 더미화

 - 가장 일반적인 범주형 변수를 변환하는 방법으로, 범주형 변수가 특정 값을 취하는지 여부를 나타내는 더미 변수를 생성하는 방법

// 추론할 수 있기 때문에.. 있으나마나한 데이터이기 때문에 그렇다.

// Tree 계열에서는 설명력을 위해서 넣는 경우도 있다.

 

* 범주형 변수 변환 방법 (2) 연속형 변수로 치환

 - 범주형 변수의 상태 공간 크기가 클 때, 더미화는 과하게 많은 변수를 추가해서 차원 저주 문제로 이어질 수 있다.

 

 - 라벨 정보를 활용하여 범주 변수를 연속형 변수로 치환하면 기존 변수가 가지는 일부 손실될 수 있고 활용이 어렵다는 단점이 있으나, 차원의 크기가 변하지 않으며 더 효율적인 변수로 변환할 수 있다는 장점이 있다.

 

 


 

[04. Part 4) Ch 18. 문자보다는 숫자 범주형 변수 문제 - 02. 관련 문법 및 실습]

* Series.unique( )

 - Seires 에 포함된 유니크한 값을 반환해주는 함수로, 상태 공간을 확인하는데 사용

 

* feature_engine.categorical_encoders.OneHotCategoricalEncoder

 - 더미화를 하기 위한 함수로, 활용 방법은 sklearn 의 인스턴스의 활용 방법과 유사하다.

 

 - 주요 입력

  . variables : 더미화 대상이 되는 범주형 변수의 이름 목록 (주의 : 해당 변수는 반드시 str 타입이어야 한다.)

  . drop_last : 한 범주 변수로부터 만든 더미 변수 가운데 마지막 더미 변수를 제거할 지를 결정

  . top_categories : 한 범주 변수로부터 만드는 더미 변수 개수를 설정하며, 빈도 기준으로 자른다.

 

 - 참고 : pandas.get_dummies( ) 는 이 함수보다 사용이 휠씬 간단하지만, 학습 데이터에 포함된 범주형 변수를 처리한 방식으로 새로 들어온 데이터에 적용이 불가능하기 때문에, 실제적으로 활용이 어렵다.

 

* 실습

// 범주형 변수 들을 판별 하고 난 다음에 더미화를 이용해서 범주 변수들을 처리 한다.

 

// pandas.Series.unique Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html

Series.unique()

Return unique values of Series object.

Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.

 

Returns

ndarray or ExtensionArray

The unique values returned as a NumPy array. See Notes.

 

// feature_engine.categorical_encoders.OneHotCategoricalEncoder Documentation

feature-engine.readthedocs.io/en/latest/encoders/OneHotCategoricalEncoder.html

classfeature_engine.categorical_encoders.OneHotCategoricalEncoder(top_categories=None, variables=None, drop_last=False)

One hot encoding consists in replacing the categorical variable by a combination of binary variables which take value 0 or 1, to indicate if a certain category is present in an observation.

Each one of the binary variables are also known as dummy variables. For example, from the categorical variable “Gender” with categories ‘female’ and ‘male’, we can generate the boolean variable “female”, which takes 1 if the person is female or 0 otherwise. We can also generate the variable male, which takes 1 if the person is “male” and 0 otherwise.

The encoder has the option to generate one dummy variable per category, or to create dummy variables only for the top n most popular categories, that is, the categories that are shown by the majority of the observations.

If dummy variables are created for all the categories of a variable, you have the option to drop one category not to create information redundancy. That is, encoding into k-1 variables, where k is the number if unique categories.

The encoder will encode only categorical variables (type ‘object’). A list of variables can be passed as an argument. If no variables are passed as argument, the encoder will find and encode categorical variables (object type).

The encoder first finds the categories to be encoded for each variable (fit).

The encoder then creates one dummy variable per category for each variable (transform).

Note: new categories in the data to transform, that is, those that did not appear in the training set, will be ignored (no binary variable will be created for them).

Parameters

  • top_categories (int, default=None) – If None, a dummy variable will be created for each category of the variable. Alternatively, top_categories indicates the number of most frequent categories to encode. Dummy variables will be created only for those popular categories and the rest will be ignored. Note that this is equivalent to grouping all the remaining categories in one group.

  • variables (list) – The list of categorical variables that will be encoded. If None, the encoder will find and select all object type variables.

  • drop_last (boolean, default=False) – Only used if top_categories = None. It indicates whether to create dummy variables for all the categories (k dummies), or if set to True, it will ignore the last variable of the list (k-1 dummies).

fit(X, y=None)[source]

Learns the unique categories per variable. If top_categories is indicated, it will learn the most popular categories. Alternatively, it learns all unique categories per variable.

Parameters

  • X (pandas dataframe of shape = [n_samples, n_features]) – The training input samples. Can be the entire dataframe, not just seleted variables.

  • y (pandas series, default=None) – Target. It is not needed in this encoded. You can pass y or None.

encoder_dict\_

The dictionary containing the categories for which dummy variables will be created.

Type

dictionary

transform(X)[source]

Creates the dummy / binary variables.

Parameters

X (pandas dataframe of shape = [n_samples, n_features]) – The data to transform.

Returns

X_transformed – The shape of the dataframe will be different from the original as it includes the dummy variables.

Return type

pandas dataframe.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 01. 특징과 라벨 간 약한 관계 및 비선형]

* 들어가기전에

 - 변수 분포 문제란 일반화된 모델을 학습하는데 어려움이 있는 분포를 가지는 변수가 있어, 일반화된 모델을 학습하지 못하는 문제로, 입문자가 가장 쉽게 무시하고 접근하기 어려워하는 문제

 

 

* 문제 정의

 - 특징과 라벨 간 관계가 없거나 매우 약하다면, 어떠한 전처리 및 모델링을 하더라도 예측력이 높은 모델을 학습할 수 없다.

 

 - 그러나 특징과 라벨 간 비선형 관계가 존재한다면, 적절한 전처리를 모델 성능을 크게 향상 시킬 수 있다.

 - Tip. 대다수의 머신러닝 모델은 선형식을 포함한다.

 

* 해결 방안

 - 가장 이상적인 해결 방안은 각 특징에 대해, 특징과 라벨 간 관계를 나타내는 그래프를 통해 적절한 특징 변환을 수행해야 한다.

// 어떤 것이 좋을지 모르기 때문에 다 만들어서 확인을 해보는 것이다.

 

 

 - 하지만 특징 개수가 많고, 다른 특징에 의한 영향도 존재하는 등 그래프를 통해 적절한 변환 방법을 선택하는 것은 쉽지 않아, 다양한 변환 방법을 사용하여 특징을 생성한 뒤 특징 선택을 수행해야 한다.

 

* 실습

// 5겹 교차 검증 기반의 평가를 수행한다.

// 로그와 제곱 관련 변수만 추가했을 뿐인데 성능이 좋아졌다.

// 특징을 선택을 할때 무조건 좋아 지는 것은 아니다.


[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 02. 이상치 제거 (1) IQR 규칙 활용]

 

* 문제 정의 및 해결 방안

 - 변수 범위에서 많이 벗어난 아주 작은 값이나 아주 큰 값으로, 일반화된 모델을 생성하는데 악영향을 끼치는 값으로 이상치를 포함하는 레코드를 제거하는 방법으로 이상치를 제거한다. (절대 추정의 대상이 아님에 주의)

 

* 이상치 판단 방법 1. IQR 규칙 활용

 - 변수별로 IQR 규칙을 만족하지 않는 샘플들을 판단하여 삭제 하는 방법

 - 직관적이고 사용이 간편하다는 장점이 있지만, 단일 변수로 이상치를 판단하기 어려운 경우가 있다는 문제가 있다. (이전 페이지의 그림에서 표시된 이상치의 X 값은 이상치라고 보기 힘든 구간에 있었음에 주목한다.)

 

 

* numpy.quantile

 - Array 의 q번째 quantile 을 구하는 함수

 - 주요 입력

  . a : input array (list, ndarray, array 등)

  . q : quantile (0 과 1 사이)

 

* 실습

// 이상치가 있는 경우를 지워줘야 한다.

// 이상치의 비율이 30% 이상일 수는 없고, 1% 미만인것이 바람직하다.

 

// numpy.quantile Documentation

numpy.org/doc/stable/reference/generated/numpy.quantile.html

numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)

 

Compute the q-th quantile of the data along the specified axis.

New in version 1.15.0.

 

Parameters

aarray_like

Input array or object that can be converted to an array.

qarray_like of float

Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.

axis{int, tuple of int, None}, optional

Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.

outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

overwrite_inputbool, optional

If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.

interpolation{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}

This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:

  • linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.

  • lower: i.

  • higher: j.

  • nearest: i or j, whichever is nearest.

  • midpoint: (i + j) / 2.

keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

 

Returns

quantilescalar or ndarray

If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

 


[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 03. 이상치 제거 (2) 밀도 기반 군집화 활용]

 

* 이상치 판단 방법 2. 밀도 기반 군집화 수행

// 특정 반경내에서는 중심점.. 중심점에 안 들어오면 경계점 그 모두에 속하지 않는 것들이 이상치라고 부른다.

 

* sklearn.cluster.DBSCAN Documentation

scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html

class sklearn.cluster.DBSCAN(eps=0.5, *, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None)

Perform DBSCAN clustering from vector array or distance matrix.

DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density.

Read more in the User Guide.

 

Parameters

epsfloat, default=0.5

The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.

min_samplesint, default=5

The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.

metricstring, or callable, default=’euclidean’

The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a Glossary, in which case only “nonzero” elements may be considered neighbors for DBSCAN.

New in version 0.17: metric precomputed to accept precomputed sparse matrix.

metric_paramsdict, default=None

Additional keyword arguments for the metric function.

New in version 0.19.

algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’

The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.

leaf_sizeint, default=30

Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.

pfloat, default=None

The power of the Minkowski metric to be used to calculate distance between points.

n_jobsint, default=None

The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 

Attributes

core_sample_indices_ndarray of shape (n_core_samples,)

Indices of core samples.

components_ndarray of shape (n_core_samples, n_features)

Copy of each core sample found by training.

labels_ndarray of shape (n_samples)

Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1.

 

* 실습

// cdist 은 DBSCAN 을 볼때 참고할 때를 위해서 가져온 library 이다.

 

// 파라미터를 조정하면서 값들을 확인한다.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 04. 특징 간 상관성 제거]

* 문제 정의

// 특징간 상관성이 높으면 강건한 파라미터 추정이 어렵다.

 

* 해결방법 (1) VIF 활용

// 다른 특징을 사용한 회귀 모델이 높은 R^2 을 보이는 경우

 

* 해결방법 (2) 주성분 분석

// 특징이 서로 직교

 

* sklearn.decomposition.PCA Documentation

scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

class sklearn.decomposition.PCA(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', random_state=None)

Principal component analysis (PCA).

Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD.

It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, depending on the shape of the input data and the number of components to extract.

It can also use the scipy.sparse.linalg ARPACK implementation of the truncated SVD.

Notice that this class does not support sparse input. See TruncatedSVD for an alternative with sparse data.

Read more in the User Guide.

 

Parameters

n_componentsint, float, None or str

Number of components to keep. if n_components is not set all components are kept:

n_components == min(n_samples, n_features)

If n_components == 'mle' and svd_solver == 'full', Minka’s MLE is used to guess the dimension. Use of n_components == 'mle' will interpret svd_solver == 'auto' as svd_solver == 'full'.

If 0 < n_components < 1 and svd_solver == 'full', select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components.

If svd_solver == 'arpack', the number of components must be strictly less than the minimum of n_features and n_samples.

Hence, the None case results in:

n_components == min(n_samples, n_features) - 1

copybool, default=True

If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead.

whitenbool, optional (default False)

When True (False by default) the components_ vectors are multiplied by the square root of n_samples and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances.

Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions.

svd_solverstr {‘auto’, ‘full’, ‘arpack’, ‘randomized’}If auto :

The solver is selected by a default policy based on X.shape and n_components: if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient ‘randomized’ method is enabled. Otherwise the exact full SVD is computed and optionally truncated afterwards.

If full :

run exact full SVD calling the standard LAPACK solver via scipy.linalg.svd and select the components by postprocessing

If arpack :

run SVD truncated to n_components calling ARPACK solver via scipy.sparse.linalg.svds. It requires strictly 0 < n_components < min(X.shape)

If randomized :

run randomized SVD by the method of Halko et al.

New in version 0.18.0.

tolfloat >= 0, optional (default .0)

Tolerance for singular values computed by svd_solver == ‘arpack’.

New in version 0.18.0.

iterated_powerint >= 0, or ‘auto’, (default ‘auto’)

Number of iterations for the power method computed by svd_solver == ‘randomized’.

New in version 0.18.0.

random_stateint, RandomState instance, default=None

Used when svd_solver == ‘arpack’ or ‘randomized’. Pass an int for reproducible results across multiple function calls. See Glossary.

New in version 0.18.0.

 

Attributes

components_array, shape (n_components, n_features)

Principal axes in feature space, representing the directions of maximum variance in the data. The components are sorted by explained_variance_.

explained_variance_array, shape (n_components,)

The amount of variance explained by each of the selected components.

Equal to n_components largest eigenvalues of the covariance matrix of X.

New in version 0.18.

explained_variance_ratio_array, shape (n_components,)

Percentage of variance explained by each of the selected components.

If n_components is not set then all components are stored and the sum of the ratios is equal to 1.0.

singular_values_array, shape (n_components,)

The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.

New in version 0.19.

mean_array, shape (n_features,)

Per-feature empirical mean, estimated from the training set.

Equal to X.mean(axis=0).

n_components_int

The estimated number of components. When n_components is set to ‘mle’ or a number between 0 and 1 (with svd_solver == ‘full’) this number is estimated from input data. Otherwise it equals the parameter n_components, or the lesser value of n_features and n_samples if n_components is None.

n_features_int

Number of features in the training data.

n_samples_int

Number of samples in the training data.

noise_variance_float

The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to compute the estimated data covariance and score samples.

Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X.

 

* 실습

// 특징간 상관 관계가 너무 크다.

// VIF 계산. LinearRegression 으로 작업한 후 R sqaure 

 

// PCA 를 활용

 


 

 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 05. 변수 치우침 제거]

 

* 문제 정의

// 치우친 반대 방향의 값(꼬리 부분) 들이 이상치 처럼 작용할 가능성이 크다.

 

* 탐색 방법 : 왜도(skewness)

 

// 왜도의 절대값이 1.5이상 이면 치우쳤다고 판단할 수 있다.

 

* scipy.stats

 - scipy.stats.mode

 - scipy.stats.skew

 - scipy.stats.kurtosis

 

* 해결방안

 

* 실습

 

// scipy.stats.mode Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html

scipy.stats.mode(a, axis=0, nan_policy='propagate')[source]

Return an array of the modal (most common) value in the passed array.

If there is more than one such value, only the smallest is returned. The bin-count for the modal bins is also returned.

Parameters

aarray_like

n-dimensional array of which to find mode(s).

axisint or None, optional

Axis along which to operate. Default is 0. If None, compute over the whole array a.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. The following options are available (default is ‘propagate’):

  • ‘propagate’: returns nan

  • ‘raise’: throws an error

  • ‘omit’: performs the calculations ignoring nan values

Returns

modendarray

Array of modal values.

countndarray

Array of counts for each mode.

 

 

//scipy.stats.skew Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html

scipy.stats.skew(a, axis=0, bias=True, nan_policy='propagate')[source]

Compute the sample skewness of a data set.

For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero means that there is more weight in the right tail of the distribution. The function skewtest can be used to determine if the skewness value is close enough to zero, statistically speaking.

 

Parameters

andarray

Input array.

axisint or None, optional

Axis along which skewness is calculated. Default is 0. If None, compute over the whole array a.

biasbool, optional

If False, then the calculations are corrected for statistical bias.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. The following options are available (default is ‘propagate’):

  • ‘propagate’: returns nan

  • ‘raise’: throws an error

  • ‘omit’: performs the calculations ignoring nan values

Returns

skewnessndarray

The skewness of values along an axis, returning 0 where all values are equal.

 

 

 

// scipy.stats.kurtosis Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html

scipy.stats.kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate')[source]

Compute the kurtosis (Fisher or Pearson) of a dataset.

Kurtosis is the fourth central moment divided by the square of the variance. If Fisher’s definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution.

If bias is False then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators

Use kurtosistest to see if result is close enough to normal.

 

Parameters

aarray

Data for which the kurtosis is calculated.

axisint or None, optional

Axis along which the kurtosis is calculated. Default is 0. If None, compute over the whole array a.

fisherbool, optional

If True, Fisher’s definition is used (normal ==> 0.0). If False, Pearson’s definition is used (normal ==> 3.0).

biasbool, optional

If False, then the calculations are corrected for statistical bias.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. ‘propagate’ returns nan, ‘raise’ throws an error, ‘omit’ performs the calculations ignoring nan values. Default is ‘propagate’.

 

Returns

kurtosisarray

The kurtosis of values along an axis. If all values are equal, return -3 for Fisher’s definition and 0 for Pearson’s definition.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 06. 스케일링]

* 문제 정의

// 특징간 스케일이 달라서 발생하는 문제이다.

// 거리 기반 모델 -> 스케일이 큰 변수에 영향을 받는 모델

// 작은것 -> 회귀모델, 서포트 벡터 머신, 신경망

// 영향이 없는 것 -> 나이브베이즈 의사결정나무

 

* 해결방법

// 스케일을 줄이는 것!

// standard Scaling 보다는 Min_max 스케일링이 좀 더 맞다고 본다.

 

* sklearn.preprocessing.MinMaxScaler & StandardScaler Documentation

- sklearn.preprocessing.MinMaxScaler

scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html

class sklearn.preprocessing.MinMaxScaler(feature_range=(0, 1), *, copy=True)

Transform features by scaling each feature to a given range.

This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.

The transformation is given by:

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min

where min, max = feature_range.

This transformation is often used as an alternative to zero mean, unit variance scaling.

Read more in the User Guide.

 

Parameters

feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.

copybool, default=True

Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).

 

Attributes

min_ndarray of shape (n_features,)

Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_

scale_ndarray of shape (n_features,)

Per feature relative scaling of the data. Equivalent to (max - min) / (X.max(axis=0) - X.min(axis=0))

New in version 0.17: scale_ attribute.

data_min_ndarray of shape (n_features,)

Per feature minimum seen in the data

New in version 0.17: data_min_

data_max_ndarray of shape (n_features,)

Per feature maximum seen in the data

New in version 0.17: data_max_

data_range_ndarray of shape (n_features,)

Per feature range (data_max_ - data_min_) seen in the data

New in version 0.17: data_range_

n_samples_seen_int

The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across partial_fit calls.

 

 

- sklearn.preprocessing.MinMaxScaler

scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html

class sklearn.preprocessing.StandardScaler(*, copy=True, with_mean=True, with_std=True)

Standardize features by removing the mean and scaling to unit variance

The standard score of a sample x is calculated as:

z = (x - u) / s

where u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False.

Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using transform.

Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual features do not more or less look like standard normally distributed data (e.g. Gaussian with 0 mean and unit variance).

For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the L1 and L2 regularizers of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.

This scaler can also be applied to sparse CSR or CSC matrices by passing with_mean=False to avoid breaking the sparsity structure of the data.

Read more in the User Guide.

 

Parameters

copyboolean, optional, default True

If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned.

with_meanboolean, True by default

If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory.

with_stdboolean, True by default

If True, scale the data to unit variance (or equivalently, unit standard deviation).

 

Attributes

scale_ndarray or None, shape (n_features,)

Per feature relative scaling of the data. This is calculated using np.sqrt(var_). Equal to None when with_std=False.

New in version 0.17: scale_

mean_ndarray or None, shape (n_features,)

The mean value for each feature in the training set. Equal to None when with_mean=False.

var_ndarray or None, shape (n_features,)

The variance for each feature in the training set. Used to compute scale_. Equal to None when with_std=False.

n_samples_seen_int or array, shape (n_features,)

The number of samples processed by the estimator for each feature. If there are not missing samples, the n_samples_seen will be an integer, otherwise it will be an array. Will be reset on new calls to fit, but increments across partial_fit calls.

 


 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 범주형 변수 문자에 대한 처리 방법

 - 이상적인 분포형에 대한 내용... 특히 스케일링. 이건 잘해야지~

 

 

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 26 회차 미션 시작]

 

* 복습

- 결측치 제거 및 groupby 등 함수 활용하기

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (2) 대표 값으로 대체]

* 대표 값으로 대체 (SimpleImpute)

 - 가장 널리 사용되는 방법이지만, (1) 소수 특징에 결측이 쏠린 경우와 (2) 특징 간 상관성이 큰 경우에는 활용하기 부적절하다.

 

 

* 관련문법 : sklearn 을 이용한 전처리 모델

 - sklearn 을 이용한 대부분의 전처리 모델의 활용 과정의 이해는 매우 중요하며, 특히 평가 데이터는 전처리 모델을 학습하는데 사용하지 않음에 주목해야 한다.

 

 

* 관련문법 : sklearn.impute.SimpleImputer

 

 - 결측이 있는 변수의 대표값으로 결측을 대체하는 인스턴스

 

 - 주요 입력

  . strategy : 대표 통계량을 지정 ('mean', 'most_frequent', 'median')

 

 - 변수 타입에 따라 두 개의 인스턴스를 같이 적용해야 할 수 있다.

 

* 실습

// 학습 데이터와 평가 데이터로 분리를 해주고.. -> model_selection 으로 통해서

 

// 대표값을 평균을 사용할지 최빈값을 사용할지 결정이 어렵다면 . 둘다 사용해야 한다.

// 데이터를 각각 분할 해서 사용한다.

 

 

// sklearn.impute.SimpleImputer Documentation

scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html

class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy='mean', fill_value=None, verbose=0, copy=True, add_indicator=False)

Imputation transformer for completing missing values.

Read more in the User Guide.

New in version 0.20: SimpleImputer replaces the previous sklearn.preprocessing.Imputer estimator which is now removed.

 

Parameters

missing_valuesnumber, string, np.nan (default) or None

The placeholder for the missing values. All occurrences of missing_values will be imputed. For pandas’ dataframes with nullable integer dtypes with missing values, missing_values should be set to np.nan, since pd.NA will be converted to np.nan.

strategystring, default=’mean’

The imputation strategy.

  • If “mean”, then replace missing values using the mean along each column. Can only be used with numeric data.

  • If “median”, then replace missing values using the median along each column. Can only be used with numeric data.

  • If “most_frequent”, then replace missing using the most frequent value along each column. Can be used with strings or numeric data.

  • If “constant”, then replace missing values with fill_value. Can be used with strings or numeric data.

New in version 0.20: strategy=”constant” for fixed value imputation.

fill_valuestring or numerical value, default=None

When strategy == “constant”, fill_value is used to replace all occurrences of missing_values. If left to the default, fill_value will be 0 when imputing numerical data and “missing_value” for strings or object data types.

verboseinteger, default=0

Controls the verbosity of the imputer.

copyboolean, default=True

If True, a copy of X will be created. If False, imputation will be done in-place whenever possible. Note that, in the following cases, a new copy will always be made, even if copy=False:

  • If X is not an array of floating values;

  • If X is encoded as a CSR matrix;

  • If add_indicator=True.

add_indicatorboolean, default=False

If True, a MissingIndicator transform will stack onto output of the imputer’s transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won’t appear on the missing indicator even if there are missing values at transform/test time.

 

Attributes

statistics_array of shape (n_features,)

The imputation fill value for each feature. Computing statistics can result in np.nan values. During transform, features corresponding to np.nan statistics will be discarded.

indicator_sklearn.impute.MissingIndicator

Indicator used to add binary indicators for missing values. None if add_indicator is False.

 

Methods

fit(X[, y])

Fit the imputer on X.

fit_transform(X[, y])

Fit to data, then transform it.

get_params([deep])

Get parameters for this estimator.

set_params(**params)

Set the parameters of this estimator.

transform(X)

Impute all missing values in X.

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (3) 근처 값으로 대체]

 

// 시계열 변수에 한정이다. 일반 변수에는 사용할 수가 없다.

 

* 근처 값으로 대체

 - 시계열 변수인 경우에는 결측이 바로 이전 값 혹은 이후 값과 유사할 가능성이 높다.

 

* 관련문법 : DataFrame.fillna

 - 결측치를 특정 값이나 방법으로 채우는 함수

 

 - 주요 입력

  . value : 결측치를 대체할 값

  . method : 결측치를 대체할 방법

   .. ffill : 결측치 이전의 유효한 값 가운데 가장 가까운 값으로 채운다.

   .. bfill : 결측치 이후의 유효한 값 가운데 가장 가까운 값으로 채운다.

 

// ffill 로 먼저 채우주고, 만약에 V2 a 처럼 NaN 앞에 Value 가 없다면 bfill 로 채워준다.

 

* 실습

// 시간 순서가 꼬이면 안된다. 시계열에 대해서만 사용할 수 있다.

// 분할하기 전에 결측치 대체가 가능한 유일한 케이스라고 보면 된다.

 

// 새로 들어온 데이터는 bfill 처럼 바로 뒤에 값을 참조하기 어렵다. 그래서 ffill 을 먼저 사용하고, bfill 을 사용한다.

 

 

// DataFrame.fillna Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

Fill NA/NaN values using the specified method.

Parameters

valuescalar, dict, Series, or DataFrame

Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list.

method{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None

Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap.

axis{0 or ‘index’, 1 or ‘columns’}

Axis along which to fill missing values.

inplacebool, default False

If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame).

limitint, default None

If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.

downcastdict, default is None

A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).

 

Returns

DataFrame or None

Object with missing values filled or None if inplace=True.

 


[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (4) 결측치 예측 모델 활용]

* 결측치 예측 모델 정의

 - 결측이 발생하지 않은 컬럼을 바탕으로 결측치를 예측하는 모델을 학습하고 활용하는 방법

 

 - (예시) V2 열에 포함된 결측 값을 추정

 

* 결측치 예측 모델 활용

 - 결측치 예측 모델은 어느 상황에서도 무난하게 활용할 수 있으나, 사용 조건 및 단점을 반드시 숙지해야 한다.

 

 - 사용 조건 및 단점

  . 조건 1. 결측이 소수 컬럼에 쏠리면 안 된다.

  . 조건 2. 특징 간에 관계가 존재해야 한다.

  . 단점 : 다른 결측치 처리 방법에 비해 시간이 오래 소요된다.

 

 

* 관련문법 : sklearn.impute.KNNImputer

 

 - 결측이 아닌 값만 사용하여 이웃을 구한 뒤, 이웃들의 값의 대표값으로 결측을 대체하는 결측치 예측 모델

 

 - 주요 입력

  . n_neighbors : 이웃 수 (주의 : 너무 적으면 결측 대체가 정상적으로 이뤄지지 않을 수 있으므로, 5 정도가 적절)

 

 

* 실습

 // n_neighbors = 5 는 크게 잡는것 보다 적당한 수치로 잡아서 인스턴스화 작업을 한다.

 

 

// sklearn.impute.KNNImputer Documentation

scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html

class sklearn.impute.KNNImputer(*, missing_values=nan, n_neighbors=5, weights='uniform', metric='nan_euclidean', copy=True, add_indicator=False)

Imputation for completing missing values using k-Nearest Neighbors.

Each sample’s missing values are imputed using the mean value from n_neighbors nearest neighbors found in the training set. Two samples are close if the features that neither is missing are close.

Read more in the User Guide.

New in version 0.22.

 

Parameters

missing_valuesnumber, string, np.nan or None, default=`np.nan`

The placeholder for the missing values. All occurrences of missing_values will be imputed. For pandas’ dataframes with nullable integer dtypes with missing values, missing_values should be set to np.nan, since pd.NA will be converted to np.nan.

n_neighborsint, default=5

Number of neighboring samples to use for imputation.

weights{‘uniform’, ‘distance’} or callable, default=’uniform’

Weight function used in prediction. Possible values:

  • ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally.

  • ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away.

  • callable : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights.

metric{‘nan_euclidean’} or callable, default=’nan_euclidean’

Distance metric for searching neighbors. Possible values:

  • ‘nan_euclidean’

  • callable : a user-defined function which conforms to the definition of _pairwise_callable(X, Y, metric, **kwds). The function accepts two arrays, X and Y, and a missing_values keyword in kwds and returns a scalar distance value.

copybool, default=True

If True, a copy of X will be created. If False, imputation will be done in-place whenever possible.

add_indicatorbool, default=False

If True, a MissingIndicator transform will stack onto the output of the imputer’s transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won’t appear on the missing indicator even if there are missing values at transform/test time.

 

Attributes

indicator_sklearn.impute.MissingIndicator

Indicator used to add binary indicators for missing values. None if add_indicator is False.

 

Methods

fit(X[, y])

Fit the imputer on X.

fit_transform(X[, y])

Fit to data, then transform it.

get_params([deep])

Get parameters for this estimator.

set_params(**params)

Set the parameters of this estimator.

transform(X)

Impute all missing values in X.


 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - sklearn.impute.SimpleImputer, fillna를 이용해서 ffill, bfill 을 어떻게 처리를 할 것인지에 대해서도 알아 보았다.

 - 결측치 예측 모델 활용 방법

 

 

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 24 회차 미션 시작]

 

* 복습

- merge, concat, apply, argsort, haversine 작업을 했었음. 

 



[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 05. 유형 (5) 데이터 요약이 포함되는 경우]

* 문제 정의 및 해결 방안

 - 보통 1 : N 병합인 경우에 사용되며, 거래 데이터 및 로그 데이터와 병합하는 경우에 주로 사용된다.

 

 - 중복 레코드를 포하하는 데이터를 요약한 후 병합 하는 방식으로 문제를 해결한다.

// 보통은 부모 데이터를 기준으로 요약을 하는 것이다.

 

* 관련문법 : DataFrame.groupby( )

 - 조건부 통계량 (조건에 따른 대상의 통계량)을 계산하기 위한 함수로 머신러닝 프로세스 뿐만 아니라, 통계 분석 등에서도 굉장히 자주 활용된다.

 

 - 주요 입력

  . by : 조건 변수 (컬럼명 혹은 컬럼명 리스트로 입력)

  . as_index : 조건 변수를 index 로 설정할 것인지 여부

 

 - 활용 예시

  . df.groupby(['성별'])['신장'].mean( ) # 성별 (조건)에 따른 신장 (대상)의 평균 (통계량)

 

* 실습

// merge 를 통해서 demo_df 에 rename 한 것을 붙이는 것이다.

 

// grouby 함수에 대해서는 지난번에도 다뤘던것 같은데, 다시 한번 중요하기에 다시금 Documentation 을 아래와 같이 첨부한다.

 

// pandas.DataFrame.groupby Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)[source]

Group DataFrame using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

 

Parameters

bymapping, function, label, or list of labels

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Split along rows (0) or columns (1).

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

as_indexbool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

sortbool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

group_keysbool, default True

When calling apply, add group keys to index to identify pieces.

squeezebool, default False

Reduce the dimensionality of the return type if possible, otherwise return a consistent type.

Deprecated since version 1.1.0.

observedbool, default False

This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers.

New in version 0.23.0.

dropnabool, default True

If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups

New in version 1.1.0.

 

Returns

DataFrameGroupBy

Returns a groupby object that contains information about the groups.

 

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 01. 문제 정의]

* 문제 정의

 - 데이터에 결측치가 있어, 모델 학습 자체가 되지 않는 문제

 

 - 결측치는 크게 NaN 과 None 으로 구분된다.

  . NaN : 값이 있어야 하는데 없는 결측으로, 대체, 추정, 예측 등으로 처리

  . None : 값이 없는게 값인 결측 (e.g., 직업 - 백수) 으로 새로운 값으로 정의하는 방식으로 처리

 

 - 결측치 처리 방법 자체는 매우 간단하나, 상황에 따른 처리 방법 선택이 매우 중요

 

* 용어 정의

 - 결측 레코드 : 결측치를 포함하는 레코드

 

 - 결측치 비율 : 결측 레코드 수 / 전체 레코드 개수


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 02. 해결 방법 (1) 삭제]

* 행 단위 결측 삭제

 - 행 단위 결측 삭제는 결측 레코드를 삭제하는 매우 간단한 방법이지만, 두 가지 조건을 만족하는 경우에만 수행할 수 있다.

 

* 열 단위 결측 삭제

 - 열 다누이 결측 삭제는 결측 레코드를 포함하는 열을 삭제하는 매우 간단한 방법이지만, 두 가지 조건을 만족하는 경우에만 사용 가능하다.

  . 소수 변수에 결측이 많이 포함되어 있다.

  . 해당 변수들이 크게 중요하지 않음 (by 도메인 지식)

 

* 관련 문법 : Series / DataFrame.isnull

 - 값이 결측이면 True 를, 그렇지 않으면 False 를 반환 (notnull 함수와 반대로 작동)

 

 - sum 함수와 같이 사용하여 결측치 분포를 확인하는데 주로 사용

 

* 관련문법 : DataFrame.dropna

 - 결측치가 포함된 행이나 열을 제거하는데 사용

 

 - 주요 입력

  . axis : 1 이면 결측이 포함된 열을 삭제하며, 0 이면 결측이 포함된 행을 삭제

  . how : 'any'면 결측이 하나라도 포함되면 삭제하며, 'all'이면 모든 갑싱 결측인 경우만 삭제 (주로 any 로 설정)

 

* 실습

// 학습데이터 기준으로 나눠야 한다.

 

// unique 한 값들을 습관적으로 찍어보는 것이 중요하다.

 

 

 

 

// pandas.DataFrame.isnull Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isnull.html

DataFrame.isnull()

Detect missing values.

Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True).

ReturnsDataFrame

Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value.

 

// pandas.Series.isnull Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isnull.html

Series.isnull()

Detect missing values.

Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True).

ReturnsSeries

Mask of bool values for each element in Series that indicates whether an element is not an NA value.

 

// pandas.DataFrame.dropna Documentation

 

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)[source]

Remove missing values.

See the User Guide for more on which values are considered missing, and how to work with missing data.

 

Parameters

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Determine if rows or columns which contain missing values are removed.

  • 0, or ‘index’ : Drop rows which contain missing values.

  • 1, or ‘columns’ : Drop columns which contain missing value.

Changed in version 1.0.0: Pass tuple or list to drop on multiple axes. Only a single axis is allowed.

how{‘any’, ‘all’}, default ‘any’

Determine if row or column is removed from DataFrame, when we have at least one NA or all NA.

  • ‘any’ : If any NA values are present, drop that row or column.

  • ‘all’ : If all values are NA, drop that row or column.

threshint, optional

Require that many non-NA values.

subsetarray-like, optional

Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include.

inplacebool, default False

If True, do operation inplace and return None.

 

Returns

DataFrame

DataFrame with NA entries dropped from it.

 

// 참고를 위해서 series에서는 어떤식으로 dropna 가 이뤄지는지 찾아보았다.

// pandas.Series.dropna Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html#pandas.Series.dropna

Series.dropna(axis=0, inplace=False, how=None)[source]

Return a new Series with missing values removed.

See the User Guide for more on which values are considered missing, and how to work with missing data.

 

Parameters

axis{0 or ‘index’}, default 0

There is only one axis to drop values from.

inplacebool, default False

If True, do operation inplace and return None.

howstr, optional

Not in use. Kept for compatibility.

 

Returns

Series

Series with NA entries dropped from it.


 

 

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 결측치 제거 및 groupby 등의 함수에 대해서 살펴 볼 수 있었다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 24 회차 미션 시작]

 

* 복습

- 파라미터 튜닝

 


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 03. 유형 (3) 포맷이 다른 키 변수가 있는 경우 (1) 참조 데이터가 필요 없는 경우]

* 참조 데이터가 필요 없는 경우의 병합

 

 - 시간과 날짜 컬럼 등은 데이터에 다라 포맷이 다른 경우가 잦음

 

 - 키 변수의 포맷이 다른 두 DataFrame 에 대해 merge 를 적용하면, 비정상적으로 병합이 이뤄질 수 있으므로, 하나의 컬럼을 다른 컬럼의 포맷에 맞게 변경해주는 작업이 필요하다.

 

* 관련 문법 : Series.apply

 

 - Series 에 있는 모든 요소에 func 을 일괄 적용하는 함수 (built-in 함수인 map 함수와 유사)

 

 - 주요 입력

  . func : Series 의 한 요소를 처리하는 함수

 

 - apply 함수는 머신러닝 코드의 효율성을 위해 굉장히 자주 사용된다.

 

* 실습

 

// df1 => 2018-01-01

// df2 => 2018년 1월 1일

// 으로 되어 있기 때문에 각각 포맷을 바꿔 줘야 한다.

 

// 함수를 짜서 각각 바꿔준다.

// 01 이 있기 때문에 int로 바꿔 준 다음에 1 의 string 타입으로 변경한것이다.

// 다음에는 merge 를 사용해서 각각 합쳐주는 방법이다.

 

// Series.apply Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html

Series.apply(func, convert_dtype=True, args=(), **kwds)

Invoke function on values of Series.

Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

Parameters

funcfunction

Python function or NumPy ufunc to apply.

convert_dtypebool, default True

Try to find better dtype for elementwise function results. If False, leave as dtype=object.

argstuple

Positional arguments passed to func after the series value.

**kwds

Additional keyword arguments passed to func.

Returns

Series or DataFrame

If func returns a Series object the result will be a DataFrame.

 


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 03. 유형 (3) 포맷이 다른 키 변수가 있는 경우 (2) 참조 데이터가 필요한 경우]

 

* 참조 데이터가 필요한 경우의 병합

 

 - 도로명 주소 / 지번 주소, 회원명 / 회원 번호 등과 같이 일정한 패턴이 없이 포맷이 다른 경우에는 컬럼 값을 참조 데이터를 이용하여 변경해야 한다.

// Series 로 되어 있는 것이 참조 데이터이다.

 

* 관련 문법 : Series.to_dict( )

 - Seires 의 Index 를 key, Data 를 Value 로 하는 사전으로 변환

 

 - replace 등 사전을 입력받는 함수를 사용할 때 주로 사용

 

* 관련문법 : Series.replace

 - dict 을 입력 받아, Series 내에 있는 요소 가운데 key 와 같은 값을 value 로 변환해줌

 

 

* 실습

// ref_df 를 사전으로 변환. set_index 로 index 를 변경해준다.

 

// add_prefix( ) 찾아보기

 

// Padnas.Series.to_dict Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html

 

Series.to_dict(into=<class 'dict'>)

Convert Series to {label -> value} dict or dict-like object.

 

Parameters

intoclass, default dict

The collections.abc.Mapping subclass to use as the return object. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized.

 

Returns

collections.abc.Mapping

Key-value representation of Series.

 

 

// Pandas.Series.replace Documenation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html

Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')

Replace values given in to_replace with value.

Values of the Series are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value.

 

Parameters

to_replacestr, regex, list, dict, Series, int, float, or None

How to find the values that will be replaced.

  • numeric, str or regex:

    • numeric: numeric values equal to to_replace will be replaced with value

    • str: string exactly matching to_replace will be replaced with value

    • regex: regexs matching to_replace will be replaced with value

  • list of str, regex, or numeric:

    • First, if to_replace and value are both lists, they must be the same length.

    • Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use.

    • str, regex and numeric rules apply as above.

  • dict:

    • Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None.

    • For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with whatever is specified in value. The value parameter should not be None in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in.

    • For a DataFrame nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with NaN. The value parameter should be None to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions.

  • None:

    • This means that the regex argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If value is also None then this must be a nested dictionary or Series.

See the examples section for examples of each of these.

valuescalar, dict, list, str, regex, default None

Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.

inplacebool, default False

If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True.

limitint, default None

Maximum size gap to forward or backward fill.

regexbool or same types as to_replace, default False

Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None.

method{‘pad’, ‘ffill’, ‘bfill’, None}

The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.

Changed in version 0.23.0: Added to DataFrame.

 

Returns

Series

Object after replacement.

 

Raises

AssertionError

  • If regex is not a bool and to_replace is not None.

TypeError

  • If to_replace is not a scalar, array-like, dict, or None

  • If to_replace is a dict and value is not a list, dict, ndarray, or Series

  • If to_replace is None and regex is not compilable into a regular expression or is a list, dict, ndarray, or Series.

  • When replacing multiple bool or datetime64 objects and the arguments to to_replace does not match the type of the value being replaced

ValueError

  • If a list or an ndarray is passed to to_replace and value but they are not the same length.

// pandas.DataFrame.add_prefix Documentation

pandas.pydata.org/docs/reference/api/pandas.DataFrame.add_prefix.html

DataFrame.add_prefix(prefix)

Prefix labels with string prefix.

For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed.

 

Parameters

prefixstr

The string to add before each label.

 

Returns

Series or DataFrame

New Series or DataFrame with updated labels.


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 04. 유형 (4) 거리 기반 병합이 필요한 경우]

* 문제 정의 및 해결 방안

 - 아파트 가격 예측 등 지역이 포함되는 문제에서 주소나 위치 변수 등을 기준으로 거리가 가까운 레코드 및 관련 통계치를 통합해야 하는 경우가 종종 있음

// 특히나 지리 데이터를 처리 할 때 많이 일어난다.

 

 - 일반적으로 (1) 각 데이터에 포함된 간 거리를 나타내는 거리 행렬을 생성하고, (2) 거리 행렬의 행 혹은 열 기준 최소 값을 가지는 인덱스를 바탕으로 이웃을 탐색한 뒤, (3) 이웃을 기존 데이터에 부착하는 방식으로 해결함

 

 

* 관련문법 : scipy.spatial.distance.cdist

 

 - 두 개의 행렬을 바탕으로 거리 행렬을 반환하는 함수

 

 - 주요 입력

  . XA : 거리 행렬 계산 대상인 행렬 (ndarray 및 DataFrame) 로, 함수 출력의 행에 해당

  . XB : 거리 행렬 계산 대상인 행렬 (ndarrary 및 DataFrame) 로, 함수 출력의 열에 해당

  . metric : 거리 척도 ('cityblock', 'correlation', 'cosine', 'euclidean', 'jaccard', 'matching' 등)

 

* 관련문법 : ndarray.argsort

 - 작은 값부터 순서대로 데이터의 위치를 반환하는 함수로, 이웃을 찾는데 주로 활용 되는 함수

 

 - 주요 입력

  . axis : 0 이면 열별 위치를, 1이면 행별 위치를 반환

 

 

* 실습

// 각각의 데이터를 merge 를 해준다. 순서를 지키면서 해야 한다. 아니면 merge 가 되지 않는다.

 

// 역에 대한 위경도로 확인한다.

// 거리 행렬 생성을 위한 컬럼들을 추출한다.

 

// 위경도 거리 계산을 위한 모듈을 설치한다.

// !pip install haversine 현실감을 위해서 이 라이브러리를 설치 한다.

!pip install haversine

pypi.org/project/haversine/

Calculate the distance (in various units) between two points on Earth using their latitude and longitude.

 

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - merge, apply, argsort, haversine 등을 배울 수 있었다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 23 회차 미션 시작]

 

* 복습

 - 지도학습할 때의 Grid 서치 및 parameterGrid 에 대해서 배울 수 있었다. 지도 학습에 대해서는 추후에 좀 더 공부가 필요할 것  같다.

 



[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 04. 복잡도 파라미터 튜닝 방법]

 

* 복잡도 파라미터 튜닝 개요

 - 복잡도 파라미터란 복잡도에 영향을 주는 파라미터로, 이 값에 따라 과적합 정도가 결정되므로 매우 신중하게 튜닝해야 한다.

// 약하다는 의미는 복잡도에 영향을 줄수도 있고 안 줄 수도 있다는 있다는 의미이다.

 

 

 

* 학습시 우연성이 개입되는 모델의 복잡도 파라미터 튜닝

// 학습할 때마다 다른 값을 가지는 모델

 - 경사하강법 등의 방법으로 학습되는 모델 (예 : 회귀모델, 신경망 등)은 초기 값에 의한 영향이 매우 크다.

 

 - 따라서 복잡도 파라미터 변화에 따른 성능 변화의 패턴을 확인하기 어려운 경우가 많으므로, seed 를 고정한 뒤 튜닝을 수행해야 한다.

// 좋은 seed 를 알 수가 없다. seed 를 고정한 뒤 여러가지 서치를 해봐야 한다.

// seed 도 하나의 축으로 들어간다고 볼 수 있다.

 

* 복잡도 파라미터 튜닝

 - seed 가 고정되어 있거나, 학습시 우연 요소가 개입되지 않는 모델의 경우에는 복잡도 파라미터에 따른 성능 변화 패턴 확인이 상대적으로 쉽다.

 

 - 복잡도 파라미터가 둘 이상인 경우에는 서로 영향을 주기 때문에 반드시 두 파라미터를 같이 조정해야 한다.

 

 - 파라미터 그리드 크기를 줄이기 위해, 몇 가지 파라미터 값을 테스트한 후 범위를 설정하는 것이 바람직하다.

 

* 실습

 

// 크로스 를 쓰면 좋겠지만 학습 데이터와 평가 데이터를 구분을 했다.

// 샘플 156 개, 특징 60 개 이 된다면 단순한 모델이 필요하다는 것이다.

// 일반적으로 단순한 모델이 좋을 가능성이 크다는 이야기이다.

 

// Case 1. 복잡도 파라미터가 한 개이면서, 단순하고, 우연성이 어느정도 있는 모델 (Logistic Regression)

// 테스트 함수 생성하고 파라미터 그리드를 통해서 튜닝을 해본다.

 

// Case 2. 복잡도 파라미터가 두 개이면서, 단순하고, 우연성이 거의 없는 모델 (Decision Tree)

// max depth 가 크고 (복잡도 증가) min_samples_leaf 가 큰 경우 (복잡도 감소) 좋은 성능이 나온다.

 

// Case 3. 복잡도 파라미터가 하나이면서, 우연성이 있는 모델 (신경망)

// (5, 5) f1 - score 가 0 이 나왔다는 것은 초기값의 영향으로 보인다.

// (10, ) 가 best score 가 나왔지만.. 좀 더 많은 판단을 위해서 확인 해봐야 한다. -> 벗어나는지 등을 결정해야 한다.


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 01. 유형 (1) 파일 자체가 나뉘어 저장된 경우]

 

 

* 개요

 - 지도학습 모델을 학습하려면 아래와 같이 반드시 하나의 통합된 데이터 집합이 필요하다.

 

- 많은 경우에 데이터가 두 개 이상으로 나뉘어져 있어, 이들을 반드시 통합하는 전처리를 수행해야 한다.

 

* 문제 정의 및 해결방안

 - 센서, 로그, 거래 데이터 등과 같이 크기가 매우 큰 데이터는 시간과 ID 등에 따라 분할되어 저장된다.

 

 - pandas.concat 함수를 사용하면 손쉽게 해결할 수 있다.

 

- 통합해야 하는 데이터가 많은 경우에는 빈 데이터 프레임을 생성한 뒤, 이 데이터 프레임과 반복문을 사용하여 불러온 데이터를 concat 함수를 이용하면 효율적으로 통합할 수 있다.

 

* 관련 문법 : pandas.concat

 - 둘 이상의 데이터 프레임을 이어 붙이는 데 사용하는 함수

 

 - 주요입력

  . objs : DataFrame 을 요소로 하는 리스트 (입력 예시 : [df1, df2]) 로 입력 순서대로 병합이 된다.

  . ignore_index : True 면 기존 인덱스를 무시하고 새로운 인덱스를 부여하며, False 면 기존 인덱스를 사용한다.

. axis : 0 이면 행 단위로 병합을 수행하며, 1 이면 열 단위로 병합을 수행한다.

 

* Tip. Axis 키워드

 - axis 키워드는 numpy 및 pandas 의 많은 함수에 사용되는 키워드로, 연산 등을 수행할 때 축의 방향을 결정하는 역할을 한다.

 

 - axis 가 0 이면 행을, 1 이면 열을 나타내지만 이렇게만 기억하면 논리적으로 이상한 점이 존재한다.

  . (예시 1) sum(axis=0) : 열 기준 합

  . (예시 2) concat([df1, df2][, axis = 0) : 행 단위 병합

 

- aixs 키워드는 그 함수의 결과 구조가 벡터 형태 (1차원) 인지, 행렬 형태 (2차원) 인지에 따라, 그 역할이 조금씩 다르다.

 

* 관련 문법 : os.listdir

 - 주요 입력

   . path : 입력된 경로 (path) 상에 있는 모든 파일명을 리스트 형태로 반환

 

* 실습

 - 5월 데이터는 평가 데이터로 쓸거고, 5월 이전 데이터는 학습데이터로 쓸것이기 때문에 이렇게 작업한다.

 

// 이 함수에 대해서는 chatper 4에서도 공부를 했어지만 다시 한번 Dcoumentation 을 참고해 본다.

// pandas.concat Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

pandas.concat(objs: Union[Iterable[‘DataFrame’], Mapping[Label, ‘DataFrame’]], axis='0', join: str = "'outer'", ignore_index: bool = 'False', keys='None', levels='None', names='None', verify_integrity: bool = 'False', sort: bool = 'False', copy: bool = 'True') → ’DataFrame’
pandas.concat(objs: Union[Iterable[FrameOrSeries], Mapping[Label, FrameOrSeries]], axis='0', join: str = "'outer'", ignore_index: bool = 'False', keys='None', levels='None', names='None', verify_integrity: bool = 'False', sort: bool = 'False', copy: bool = 'True') → FrameOrSeriesUnion

Concatenate pandas objects along a particular axis with optional set logic along the other axes.

Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number.

 

Parameters

objsa sequence or mapping of Series or DataFrame objects

If a mapping is passed, the sorted keys will be used as the keys argument, unless it is passed, in which case the values will be selected (see below). Any None objects will be dropped silently unless they are all None in which case a ValueError will be raised.

axis{0/’index’, 1/’columns’}, default 0

The axis to concatenate along.

join{‘inner’, ‘outer’}, default ‘outer’

How to handle indexes on other axis (or axes).

ignore_indexbool, default False

If True, do not use the index values along the concatenation axis. The resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join.

keyssequence, default None

If multiple levels passed, should contain tuples. Construct hierarchical index using the passed keys as the outermost level.

levelslist of sequences, default None

Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys.

nameslist, default None

Names for the levels in the resulting hierarchical index.

verify_integritybool, default False

Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation.

sortbool, default False

Sort non-concatenation axis if it is not already aligned when join is ‘outer’. This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

New in version 0.23.0.

Changed in version 1.0.0: Changed to not sort by default.

copybool, default True

If False, do not copy data unnecessarily.

 

Returns

object, type of objs

When concatenating all Series along the index (axis=0), a Series is returned. When objs contains at least one DataFrame, a DataFrame is returned. When concatenating along the columns (axis=1), a DataFrame is returned.

 


[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 02. 유형 (2) 명시적인 키 변수가 있는 경우]

* 문제 정의 및 해결 방안

 - 효율적인 데이터 베이스 관리를 위해, 잘 정제된 데이터일지라도 데이터가 키 변수를 기준으로 나뉘어 저장되는 경우가 매우 흔함

 

 - SQL 에서는 JOIN 을 이용하여 해결하며, python 에서는 merge 를 이용하여 해결한다.

 - 일반적인 경우는 해결이 어렵지 않지만, 다양한 케이스가 존재할 수 있으므로 반드시 핵심을 기억해야 한다.

  (1) 어느 컬럼이 키 변수 역할을 할 수 있는지 확인하고, 키 변수를 통일해야 한다.

  (2) 레코드의 단위를 명확히 해야 한다.

 

* 관련문법 : pandas.merge

 - 키 변수를 기준으루 두개의 데이터 프레임을 병합(join)하는 함수

 

 - 주요입력

   . left : 통합 대상 데이터 프레임 1

   . right : 통합 대상 데이터 프레임 2

   . on : 통합 기준 key 변수 및 변수 리스트 (입력을 하지 않으면, 이름이 같은 변수를 key 로 식별함)
   . left_on : 데이터 프레임 1의 key 변수 및 변수 리스트
   . right_on : 데이터 프레임 2의 key 변수 및 변수 리스트
   . left_index : 데이터 프레임 1의 인덱스를 key 변수로 사용할 지 여부
   . right_index : 데이터 프레임 2의 인덱스를 key 변수로 사용할 지 여부

 

* 실습

 - on 을 안써도 되긴 하지만, 가능하면 작성해주는 것이 더 좋다.

 

// 이 함수도 다시

// pandas.merge Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

 

DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes='_x', '_y', copy=True, indicator=False, validate=None)[source]

Merge DataFrame or named Series objects with a database-style join.

The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on.

Parameters

rightDataFrame or named Series

Object to merge with.

how{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’

Type of merge to be performed.

  • left: use only keys from left frame, similar to a SQL left outer join; preserve key order.

  • right: use only keys from right frame, similar to a SQL right outer join; preserve key order.

  • outer: use union of keys from both frames, similar to a SQL full outer join; sort keys lexicographically.

  • inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys.

onlabel or list

Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.

left_onlabel or list, or array-like

Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.

right_onlabel or list, or array-like

Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns.

left_indexbool, default False

Use the index from the left DataFrame as the join key(s). If it is a MultiIndex, the number of keys in the other DataFrame (either the index or a number of columns) must match the number of levels.

right_indexbool, default False

Use the index from the right DataFrame as the join key. Same caveats as left_index.

sortbool, default False

Sort the join keys lexicographically in the result DataFrame. If False, the order of the join keys depends on the join type (how keyword).

suffixeslist-like, default is (“_x”, “_y”)

A length-2 sequence where each element is optionally a string indicating the suffix to add to overlapping column names in left and right respectively. Pass a value of None instead of a string to indicate that the column name from left or right should be left as-is, with no suffix. At least one of the values must not be None.

copybool, default True

If False, avoid copy if possible.

indicatorbool or str, default False

If True, adds a column to the output DataFrame called “_merge” with information on the source of each row. The column can be given a different name by providing a string argument. The column will have a Categorical type with the value of “left_only” for observations whose merge key only appears in the left DataFrame, “right_only” for observations whose merge key only appears in the right DataFrame, and “both” if the observation’s merge key is found in both DataFrames.

validatestr, optional

If specified, checks if merge is of specified type.

  • “one_to_one” or “1:1”: check if merge keys are unique in both left and right datasets.

  • “one_to_many” or “1:m”: check if merge keys are unique in left dataset.

  • “many_to_one” or “m:1”: check if merge keys are unique in right dataset.

  • “many_to_many” or “m:m”: allowed, but does not result in checks.

Returns

DataFrame

A DataFrame of the two merged objects.


 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 복잡도 파라미터 튜닝에서는 다양한 파라미터에 대해서 어떤식을 튜닝을 해야 되는지.. 단순하다고 나쁜 것도 아니고 복잡하다고 좋은 것도 아니라.. 그 상황에 맞는 경험치!!^^!!

- 데이터 합치 파트는 Chapter 4 에 나와 있는 함수들을 다시 한번 되돌아 볼 수 있는 기회였다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 22 회차 미션 시작]

 

* 복습

 - 모델 개발 프로세스에 대해서 배웠고, 지도학습에서는 선형회귀, 의사결정나무, 신경망 등에 대해서도 배워 볼 수 있었다.


[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 01. 그리드 서치]

* 모델 및 파라미터 선정 문제

 - 어떠한 데이터에 대해서도 우수한 모델과 그 하이퍼 파라미터는 절대 존재하지 않는다.

 - 또한, 분석적인 방법으로 좋은 모델과 하이퍼 파라미터를 선정하는 것도 불가능하다.

 

* 그리드 서치 개요

 - 하이퍼 파라미터 그리드는 한 모델의 하이퍼 파라미터 조합을 나타내며, 그리드 서치란 하이퍼 파라미터 그리드에 속한 모든 파라미터 조합을 비교 평가하는 방법을 의미

 

// 거리 척도

 - 예시 : k - 최근접 이웃의 파라미터 그리드

 => 총 여섯 개의 하이퍼 파라미터 조합에 대한 성능을 평가하여, 그 중 가장 우수한 하이퍼 파라미터를 선택

 

* 그리드 서치 코드 구현

 - sklearn 을 활용하여 그리드 서치를 구현하려면 사전 형태로 하이퍼 파라미터 그리드를 정의해야 한다.

  . key: 하이퍼 라미터명(str)

  . value : 해당 파라미터의 범위 (list)

 

 

* 그리드 서치 코드 구현 : GridSearchCV

 - sklearn.model_selection.GridSearchCV

  . 주요 입력

   .. estimator : 모델 (sklearn 인스턴스)

   .. param_grid : 파라미터 그리드 (사전)

   .. cv : k 겹 교차 검증에서의 k (2 이상의 자연수)

   .. scoring_func : 평가 함수 (sklearn 평가 함수)

 

  . GridSearchCV 인스턴스(GSCV) 의 주요 method 및 attribute

   .. GSCV = GridSearchCV (estimator, param_grid, cv, scoring_func) : 인스턴스화

   .. GSCV.fit(X, Y) : 특징 벡터 X 와 라벨 Y 에 대해 param_grid 에 속한 파라미터를 갖는 모델을 k - 겹 교차 검증 방식으로 평가하여, 그 중 가장 우수한 파라미터를 찾는다.

   .. GSCV.get_params( ) : 가장 우수한 파라미터를 반환

 

 . 사용이 편하다는 장점이 있지만, k - 겹 교차 검증 방식을 사용하기에 느리고, 성능 향상을 위한 전처리 기법을 적용할 수 없다는 단점이 있다.

 

* 그리드 서치 코드 구현 : ParameterGrid

 - sklearn.model_selection.ParameterGrid

  . param_grid (사전 형태의 하이퍼 파라미터 그리드) 를 입력 받아, 가능한 모든 파라미터 조합 (사전) 을 요소로 하는 generator 를 반환하는 함수

  . GridSearchCV 에 비해 사용이 어렵다는 단점이 있지만, 성능 향상을 위한 전처리 기법을 적용하는데 문제가 없어서 실무에서 휠씬 자주 사용된다.

 

* ParameterGrid 사용을 위해 알아야 하는 문법 (1/2)

 - 파이썬 함수의 입력으로 사전 자료형을 사용하는 경우에는 ** 를 사전 앞에 붙여야 한다.

- 이를 활용하면, ParameterGrid 인스턴스를 순회하는 사전 자료형인 변수(파라미터)를 모델의 입력으로 넣을 수 있다.

 

* ParameterGrid 사용을 위해 알아야 하는 문법 (2/2)

 - ParameterGrid 인스턴스를 순회하면서 성능이 가장 우수한 값을 찾으려면 최대값(최소값) 을 찾는 알고리즘을 알아야 한다.

  . 내장 함수인 max 함수나 min 함수를 사용해도 되지만, 평가해야 하는 하이퍼 파라미터 개수가 많으면 불필요한 메모리 낭비로 이어질 수 있으며, 더욱이 모델도 같이 추가되야 하므로 메모리 에러로 이어지기 쉽다.

 

 - 알고리즘 예시 : L = [10, 20, 30, 10, 20] 에서의 최대닶을 찾아라.

 

* 실습

// 비교를 위해서 list 형태로 바꿔준다.

// 실제로는 바꿔주지 않고 parametergrid(grid) 로 순회한다.

 

// a 와 b 의 순서는 크게 상관이 없다.

 

// max_value 는 메우 작은 값을 설정 한다. 음의 무한대를 주는 것이 좋지만, domain 이 있으면 그 가장 값을 지정한다.

 

// 최소값 min_value 는 매우 큰 값으로 잡아 준다. 나머지는 동일하게 적용한다.

 

// 모델은 여러가지로 적용해보는 것이 좋다.

 

 

// sklearn.model_selection.GridSearchCV Documentation

scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

class sklearn.model_selection.GridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, iid='deprecated', refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False)

Exhaustive search over specified parameter values for an estimator.

Important members are fit, predict.

GridSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.

The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid.

Read more in the User Guide.

Parameters

estimatorestimator object.

This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed.

param_griddict or list of dictionaries

Dictionary with parameters names (str) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.

scoringstr, callable, list/tuple or dict, default=None

A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set.

For evaluating multiple metrics, either give a list of (unique) strings or a dict with names as keys and callables as values.

NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each.

See Specifying multiple metrics for evaluation for an example.

If None, the estimator’s score method is used.

n_jobsint, default=None

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

Changed in version v0.20: n_jobs default changed from 1 to None

pre_dispatchint, or str, default=n_jobs

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:

  • None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs

  • An int, giving the exact number of total jobs that are spawned

  • A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’

iidbool, default=False

If True, return the average score across folds, weighted by the number of samples in each test set. In this case, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.

Deprecated since version 0.22: Parameter iid is deprecated in 0.22 and will be removed in 0.24

cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:

  • None, to use the default 5-fold cross validation,

  • integer, to specify the number of folds in a (Stratified)KFold,

  • CV splitter,

  • An iterable yielding (train, test) splits as arrays of indices.

For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used.

Refer User Guide for the various cross-validation strategies that can be used here.

Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.

refitbool, str, or callable, default=True

Refit an estimator using the best found parameters on the whole dataset.

For multiple metric evaluation, this needs to be a str denoting the scorer that would be used to find the best parameters for refitting the estimator at the end.

Where there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given cv_results_. In that case, the best_estimator_ and best_params_ will be set according to the returned best_index_ while the best_score_ attribute will not be available.

The refitted estimator is made available at the best_estimator_ attribute and permits using predict directly on this GridSearchCV instance.

Also for multiple metric evaluation, the attributes best_index_, best_score_ and best_params_ will only be available if refit is set and all of them will be determined w.r.t this specific scorer.

See scoring parameter to know more about multiple metric evaluation.

Changed in version 0.20: Support for callable added.

verboseinteger

Controls the verbosity: the higher, the more messages.

error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.

return_train_scorebool, default=False

If False, the cv_results_ attribute will not include training scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance.

New in version 0.19.

Changed in version 0.21: Default value was changed from True to False

Attributes

cv_results_dict of numpy (masked) ndarrays

A dict with keys as column headers and values as columns, that can be imported into a pandas DataFrame.

For instance the below given table

 

           

param_kernel

param_gamma param_degree split0_test_score…

 

rank_t…

‘poly’

2

0.80

2

‘poly’

3

0.70

4

‘rbf’

0.1

0.80

3

‘rbf’

0.2

0.93

1

 

will be represented by a cv_results_ dict of:

{ 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.80, 0.70, 0.80, 0.93], 'split1_test_score' : [0.82, 0.50, 0.70, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.85], 'std_test_score' : [0.01, 0.10, 0.05, 0.08], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.80, 0.92, 0.70, 0.93], 'split1_train_score' : [0.82, 0.55, 0.70, 0.87], 'mean_train_score' : [0.81, 0.74, 0.70, 0.90], 'std_train_score' : [0.01, 0.19, 0.00, 0.03], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.01, 0.06, 0.04, 0.04], 'std_score_time' : [0.00, 0.00, 0.00, 0.01], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], }

NOTE

The key 'params' is used to store a list of parameter settings dicts for all the parameter candidates.

The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds.

For multi-metric evaluation, the scores for all the scorers are available in the cv_results_ dict at the keys ending with that scorer’s name ('_<scorer_name>') instead of '_score' shown above. (‘split0_test_precision’, ‘mean_train_precision’ etc.)

best_estimator_estimator

Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.

See refit parameter for more information on allowed values.

best_score_float

Mean cross-validated score of the best_estimator

For multi-metric evaluation, this is present only if refit is specified.

This attribute is not available if refit is a function.

best_params_dict

Parameter setting that gave the best results on the hold out data.

For multi-metric evaluation, this is present only if refit is specified.

best_index_int

The index (of the cv_results_ arrays) which corresponds to the best candidate parameter setting.

The dict at search.cv_results_['params'][search.best_index_] gives the parameter setting for the best model, that gives the highest mean score (search.best_score_).

For multi-metric evaluation, this is present only if refit is specified.

scorer_function or a dict

Scorer function used on the held out data to choose the best parameters for the model.

For multi-metric evaluation, this attribute holds the validated scoring dict which maps the scorer key to the scorer callable.

n_splits_int

The number of cross-validation splits (folds/iterations).

refit_time_float

Seconds used for refitting the best model on the whole dataset.

This is present only if refit is not False.

New in version 0.20.

 

 

// sklearn.model_selection.ParameterGrid Documentation

scikit-learn.org/stable/modules/generated/sklearn.model_selection.ParameterGrid.html

 

class sklearn.model_selection.ParameterGrid(param_grid)[source]

Grid of parameters with a discrete number of values for each.

Can be used to iterate over parameter value combinations with the Python built-in function iter.

Read more in the User Guide.

Parametersparam_griddict of str to sequence, or sequence of such

The parameter grid to explore, as a dictionary mapping estimator parameters to sequences of allowed values.

An empty dict signifies default parameters.

A sequence of dicts signifies a sequence of grids to search, and is useful to avoid exploring parameter combinations that make no sense or have no effect. See the examples below.

 


 

[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 02. 기준 (1) 변수 타입]

* 변수 타입 확인 방법

 - DataGrame.dtypes

  . DataFrame 에 포함된 컬럼들의 데이터 타입 ( object, int64, float64, bool 등 ) 을 반환

 

 - DataFrame.infer_objects( ).dtypes

  . DataFrame 에 포함된 컬럼들의 데이터 타입을 추론한 결과를 반환

  . (예) ['1', '2'] 라는 값을 가진 컬럼은 비록 object 타입이나, int 타입이라고 추론할 수 있다.

 

 - 주의 : string type 이라고 해서 반드시 범주형이 아니며, int 혹은 float type 이라고 해서 반드시 연속형은 아니다. 반드시 상태 공간의 크기와 도메인 지식 등을 고려해야 한다.

 

* 변수 타입에 따른 적절한 모델

 - 주의 : 모델 성능에는 변수 타입만 영향을 주는 것이 아니므로, 다른 요소도 반드시 고려해야 한다.

 

* 혼합형 변쉥 적절하지 않은 모델 (1) 회귀 모델

 - 혼합형 변수인 경우에는 당연히 변수의 스케일 차이가 존재하는 경우가 흔하다.

 

 - 변수의 스케일에 따라 계수 값이 크게 달라지므로, 예측 안정성이 크게 떨어진다.

  . 모든 특징이 라벨에 독립적으로 영향을 준다면, 이진형 특징의 계수 절대값이 스케일이 큰 연속형 특징의 계수 절대값 보다 크게 설정된다.

  . 이진형 특징 값에 따라 예측 값이 크게 변동한다.

 

 - 스케일일ㅇ을 하더라도 이진형 특징의 분포가 변하지 않으므로, 이진형 특징의 값에 따른 영향력이 크게 줄지 않는다. 

 

* 혼합형 변수에 적절하지 않은 모델 (2) 나이브 베이즈

 - 나이브베이즈는 하나의 확률 분포를 가정하기 때문에, 혼합형 변수를 가지는 데이터에 부적절하다.

  . (예시) 베르누이 분포는 연속형 값을 가지는 확률 분포 추정에 매우 부적절

 

 - 따라서 나이브베이즈는 혼합형 변수인 경우에는 절대로 고려해서는 안 되는 모델이다.

 

* 혼합형 변수에 적절하지 않은 모델 (3) k - 최근접 이웃

 - 스케일이 큰 변수에 의해 거리가 사실상 결정되므로, k-NN 은 혼합형 변수에 적절하지 않다.

 

 - 단, 코사인 유사도를 사용하는 경우나, 스케일링을 적용하는 경우에는 큰 무리 없이 사용 가능하다.

 


 

[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 03. 기준 (2) 데이터 크기]

* 샘플 개수와 특징 개수에 따른 과적합 (remind)

 

* 샘플 개수와 특징 개수에 따른 적절한 모델

 

* 실습

// random_state 가 있는 모델은 모두 같은 값으로 설정한다.

 

// 모델별 k 겹 교차 검증 기반 (k=5) 의 MAE 값으로 계산한다.

 

// cv 는 폴더의 갯수. k 값

 

// 특징이 적으면 복잡한 모델은 나오기 어렵다.

 

// 샘플이 매우 적고 특징이 상대적으로 많은 경우

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 지도학습할 때의 Grid 서치 및 parameterGrid 에 대해서 배울 수 있었다. 동영상 순서가 이상해서 처음엔 약간 이상했지만~^^;;

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트