2013-08-23 4 views
4

Scikit에서 NB 분류를 수행하기 위해 맞춤 데이터를로드하려고합니다. Scikit에 샘플 데이터를로드하고 NB를 수행하는 데 도움이 필요합니다. 대상에 대한 범주 값을로드하는 방법scikit에서 CSV 데이터를로드하고 Naive Bayes 분류에 사용하는 방법

Train and Test에 대해 동일한 데이터를 사용하거나 테스트 용으로 완전한 세트를 사용하십시오.

Sl No,Member ID,Member Name,Location,DOB,Gender,Marital Status,Children,Ethnicity,Insurance Plan ID,Annual Income ($),Twitter User ID 
1,70000001,Fly Dorami,New York,39786,M,Single,,Asian,2002,0,548900028 
2,70000002,Bennie Ariana,Pennsylvania,6/24/1940,F,Single,,Caucasian,2002,66313, 
3,70000003,Brad Farley,Pennsylvania,12001,F,Married,4,African American,2002,98444, 
4,70000004,Daggoo Cece,Indiana,14032,F,Married,2,Hispanic,2001,41896,113481472. 

답변

11

다음을 시작하면 팬더와 numpy가 필요합니다. .csv를 데이터 프레임에로드하고이를 사용하여 모델에 입력 할 수 있습니다. 따라서 분리하려는 대상에 따라 목표를 정의해야합니다 (음수의 경우 0, 양성의 경우 1, 이진 분류로 가정).

from sklearn.naive_bayes import GaussianNB 
import pandas as pd 
import numpy as np 

# create data frame containing your data, each column can be accessed # by df['column name'] 
df = pd.read_csv('/your/path/yourFile.csv') 

target_names = np.array(['Positives','Negatives']) 

# add columns to your data frame 
df['is_train'] = np.random.uniform(0, 1, len(df)) <= 0.75 
df['Type'] = pd.Factor(targets, target_names) 
df['Targets'] = targets 

# define training and test sets 
train = df[df['is_train']==True] 
test = df[df['is_train']==False] 

trainTargets = np.array(train['Targets']).astype(int) 
testTargets = np.array(test['Targets']).astype(int) 

# columns you want to model 
features = df.columns[0:7] 

# call Gaussian Naive Bayesian class with default parameters 
gnb = GaussianNB() 

# train model 
y_gnb = gnb.fit(train[features], trainTargets).predict(train[features]) 
+0

해결책 주셔서 감사합니다, 대상 예제 "결혼 상태"를 먹이십시오. 이 프로그램을 실행할 때부터 df [ 'Type'] = pd.Factor (targets, target_names) 줄의 정의되지 않은 오류 대상을 얻습니다. –

+0

배열을 대상으로 정의해야하며 0과 1을 포함하는 단일 colunm이어야합니다 if df [ 'Type'] = pd.Factor (targets, target_names)를 호출하기 전에 바이너리 분류를 수행해야합니다. 당신은 당신의 분류 문제에 대해 좀 더 많은 정보를 줄 수 있습니까? – rlmlr

+0

위 코드는 설명이지만 "targets"변수가 누락되었습니다. 추가 할 수 있습니까? –