Skip to content
mahler83 blog v2

Pharmacology, IoT, LLMs

mahler83 blog v2

Pharmacology, IoT, LLMs

python missForest imputation for mixed categorical and continuous features example

python missForest imputation for mixed categorical and continuous features example

mahler83, 2019-09-092019-09-09

R에서 연속형 변수와 범주형 변수가 섞여있어도 missForest imputation이 한 줄로 되는데, python에서는 은근 까다롭다.

import numpy as np
import pandas as pd
from missingpy import MissForest
RS = 100

일단 필요한 라이브러리 로드. missingpy 패키지를 이용

data = pd.read_csv('inhadr.csv', na_values=['-100', '-1000'])
del data["ID"] #patient id not needed
del data['AST'] # should be blinded for finding DILI patients
del data['ALT'] # should be blinded for finding DILI patients
data['SEX'] = data.SEX.astype('category')
data['GENOTYPE_RESULT'] = data.GENOTYPE_RESULT.astype('category')

성별과 유전형이 category이다.

%%time
# get indices of categorical features
cat_cols = [data.columns.get_loc(col) for col in data.select_dtypes(['category']).columns.tolist()]
# missForest imputation
imputer = MissForest(random_state=RS)
imputed = imputer.fit_transform(data, cat_vars=cat_cols)

범주형인 컬럼의 번호를 리스트 형태로 전달해줘야 한다. R에서는 웬만하건 다 이름 index로도 되는데 왜 꼭 번호를…

imputed = pd.DataFrame(imputed, columns=data.columns.tolist())
for col in cat_cols:
    imputed.iloc[:,col] = imputed.iloc[:,col].astype('category')
imputed.describe(include='all')

내가 잘못한건지 모르겠는데, imputation이 끝나고 나면 dtype이 다 float64로 변환된다. 다시 category 형태로 변경

Share this:

  • Twitter
  • Facebook
Machine Learning missForestpython

Post navigation

Previous post
Next post

Related Posts

AI

모든 의학 문제를 처리하는 GMAI가 나올 것 – 네이처 논문 2023.4

2023-04-142023-07-19

의학 분야 전반에 대한 작업을 처리할 수 있는 foundation model "Generalist Medical AI"가 나올 것이라는 네이처 perspective 논문 (2022/11/3) 그제 공개됐는데 투고 자체는 ChatGPT전에 이루어진 논문이네 https://www.nature.com/articles/s41586-023-05881-4 ChatGPT 언급이 된 걸 보니 리비전하면서 introduction이 좀 고쳐진 듯 기존에는 X-ray에 폐렴이다 아니다 레이블링해서 "폐렴을 X-ray를 진단하는 모델"을 만들었다면 앞으로는 task-specific model에서…

Share this:

  • Twitter
  • Facebook
Read More
Generative AI

자연어 의무기록에 생성모델을 적용해 미래 건강 예측

2023-01-012023-01-02

의무기록은 자연어로 되어있어서 활용하기 어렵다 같은 소리를 하던 시절은 정말 저물어가는 것 같다. Foresight — Deep Generative Modelling of Patient Timelines using Electronic Health Recordshttps://arxiv.org/abs/2212.08072 환자의 의무기록 텍스트에서 의학 용어를 추출해서 timeline 형태로 만듦 (중간에 나이가 들면 나이 먹는 이벤트 삽입)이걸 GPTv2로 학습시켜 앞으로 어떤 이벤트들이 일어날지 예측 대단하다 싶은…

Share this:

  • Twitter
  • Facebook
Read More
Machine Learning

트리기반 모델이 뉴럴넷보다 테이블형 데이터에서 성능이 좋은 이유

2022-12-312023-01-02

환자 데이터로 예측모델 만들어 분석하는 연구를 하면 대부분의 경우 Tree-based model (XGBoost, Random Forest, Gradient Boosting Tree, AdaBoost)들의 성능이 높게 나오는 것을 경험적으로 알고 있었는데, 왜 그런지 연구한 논문. 이런 건 나도 해볼 수 있었을텐데?싶음 https://arxiv.org/pdf/2207.08815.pdf 결론: Neural network는 smooth function을 fitting하는 경향이 있기 때문에 irregular function을 가지는 경우 약함…

Share this:

  • Twitter
  • Facebook
Read More

Comments (2)

  1. Abhilash says:
    2020-03-27 at 01:42

    Hi!

    I tried your code on 2 of my datasets and still get the error related to categorical vars: “could not convert string to float: ‘RL”. I wonder what I’m missing:

    from missingpy import MissForest
    imputer = MissForest()
    imputed = imputer.fit_transform(X_train, cat_vars= [X_train.columns.get_loc(col) for col in X_train.select_dtypes([‘category’]).columns.tolist()])

    imputed = pd.DataFrame(imputed, columns=X_train.columns.tolist())
    for col in catColIndices:
    imputed.iloc[:,col] = imputed.iloc[:,col].astype(‘category’)
    imputed.describe(include=’all’)

    Kindly help me out.

    Thank you!

    Reply
    1. mahler83 says:
      2020-04-03 at 12:07

      Hi Abhilash,
      According to your error message, there seems to be some error while converting a string to float.
      I assume your categorical values (such as RL) are not using numeric coding.
      In my case, SEX and GENOTYPE_RESULT were entered as {0, 1} and {0, 1, 2, 3}
      Try using numeric coding, not raw text in your categorical values.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
  1. mahler83 on 공부 잘하는 과학적 방법 – Weinstein 2018.12023-07-30

    접속자가 갑자기 늘어서 홈페이지가 오동작을 했습니다. 시간이 지나면 나아질 것 같습니다.

  2. SkyHigh on 공부 잘하는 과학적 방법 – Weinstein 2018.12023-07-30

    PC에선 잘 보이는데 모바일(아이폰)에선 한번 보이고 이후부턴 계속 나오질 않네요. 뭔가 문제가 있어보입니다. 한번 확인해봐주세요

  3. mahler83 on DadGPT 한자능력검정시험 교재 4급II (자체제작)2023-07-19

    참고로 이번 주가 어문회 시험 신청 기간입니다. 좋은 결과 있으시길!

  4. Jin on DadGPT 한자능력검정시험 교재 4급II (자체제작)2023-07-19

    감사합니다~ 어이 말고 재가 해야 겠어요~

  5. mahler83 on GPT에게 한의사 국시를 풀게 했더니 57% 정답률 – 2023.32023-06-14

    안녕하세요, 댓글이 스팸필터에 걸려있어 뒤늦게 확인했습니다. 트위터에서 멘션이나 DM주셔도 되는데 번거로운 방식을 선택하신 이유가 궁금하네요. 일단 메일 드리겠습니다.

  • 3D Printing
  • Academic writing
  • Adsense
  • AI
  • AWS
  • Creativity
  • DIY
  • favorites
  • Gaming
  • Generative AI
  • hands-on
  • Home Assistant
  • Ideas
  • IT
  • Lab Stuff
  • Large language model
  • Law
  • Machine Learning
  • Medical Education
  • Medicine
  • My Thoughts
  • Neuroscience
  • Parenting
  • Pedagogy
  • Pharmacology
  • PHP
  • PokemonGo
  • Precision medicine
  • Reasoning
  • Science
  • Social studies
  • Statistics and Math
  • Tips & Techs
  • Twitter API
  • Ubuntu
  • Uncategorized
  • Web development
  • Web News
©2023 mahler83 blog v2 | WordPress Theme by SuperbThemes