2017-12-06 2 views
0

입력 된 텍스트가 공상 과학 소설에서 나온 것인지 아닌지 예측하기 위해 데이터 집합을 학습하려고합니다. 필자는 파이썬에 비교적 익숙하지 않기 때문에 내가 뭘 잘못하고 있는지 정확히 알지 못합니다.데이터 프레임을 사용하여 데이터 모델링

코드 :

#class17.py 
""" 
Created on Fri Nov 17 14:07:36 2017 

@author: twaters 

Read three science fiction novels 
Predict a sentence or paragraph 
see whether sentence/phrase/book is from a science fiction novel or not 
""" 

import nltk 
import pandas as pd 
import csv 
from sklearn.metrics import accuracy_score 
from sklearn.linear_model import LogisticRegression 

from sklearn import model_selection 
from sklearn.metrics import confusion_matrix 
from sklearn.metrics import classification_report 
from nltk.corpus import stopwords 

#nltk.download() 


irobot = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/irobot.txt" 
enders_game = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/endersgame.txt" 
space_odyssey ="C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/spaceodyssey.txt" 
to_kill_a_mockingbird = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/tokillamockingbird.txt" 

sr = set(stopwords.words('english')) 
freq = {} 

def main(): 
    #read_novels() 
    model_novels() 


def read_novel(b, is_scifi): 

    read_file = open(b) 

    text = read_file.read() 
    words = text.split() 
    clean_tokens = words[:] 
    filtered_list = [] 

    for word in clean_tokens: 
     word = word.lower() 
     if word not in sr: 
      filtered_list.append(word) 

    freq = nltk.FreqDist(clean_tokens) 
    #print(filtered_list) 
    for word in clean_tokens: 
     count = freq.get(word,0) 
     freq[word] = count + 1 



    frequency_list = freq.keys() 

    with open('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'w', encoding='utf-8') as csvfile: 
     fieldnames = ['word','frequency','is_scifi'] 
     writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator = '\n') 
     writer.writeheader() 

     for words in frequency_list: 
      writer.writerow({'word': words,'frequency': freq[words],'is_scifi':is_scifi}) 

    print("List compiled.") 

def read_novels(): 

    read_novel(enders_game, 0) 
    read_novel(space_odyssey, 0) 
    read_novel(irobot, 0) 
    read_novel(to_kill_a_mockingbird, 1) 

def model_novels(): 

    df = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'rb', delimiter='\t', encoding='utf-8') 
    print(df) 

    #for index in range(2, df.shape[0], 100): 
    df_subset = df.loc[1:] 
    #print(df_subset) 
    X = df_subset.loc[:, 'frequency':'is_scifi'] 
    Y = df_subset.loc[:, 'frequency':'is_scifi'] 
    testing_size = 0.2 
    seed = 7 
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed) 

    selectedModel = LogisticRegression() 
    selectedModel.fit(X_train, Y_train) 
    predictions = selectedModel.predict(X_validation) 

#%% 
#print("Accuracy Score:\n", accuracy_score(Y_validation, predictions)) 
#print("Confusion Matrix:\n",confusion_matrix(predictions, Y_validation)) 
#print("Class report:\n", classification_report(Y_validation, predictions)) 
#df_test = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', delimiter='\t') 
#predictions_test = selectedModel.predict(df_test) 
#test_frame = pd.DataFrame(predictions_test) 
#test_frame.to_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data_result.txt', sep='\t') 

오류 : 역 추적 (가장 최근 통화 최종) :

파일 "", 줄 1, 주()

파일에서 "C :/Users/user/desktop/Assignments/SQL/Python/DA Project/class17.py ", 줄 36, 기본 model_novels()

파일 : model_novels selectedModel.fit (X_train, Y_train)

파일 "D에서"C/사용자/사용자/데스크탑/할당/SQL/파이썬/DA 프로젝트/class17.py ", 라인 95 : \ Program Files (x86) \ Anaconda \ lib \ site-packages \ sklearn \ linear_model \ logistic.py ", 줄 1216, 맞음

파일"D : \ 아나콘다 \ lib 디렉토리의 \ 사이트 - 패키지 \ sklearn \ UTILS \ validation.py ", 라인 573, check_X_y에서 ensure_min_features, warn_on_dtype, 추정)

파일"D : \ 프로그램 파일 (86) \ 아나콘다 \ LIB \ 앉아 (어레이)

파일 "D : \ Program Files (x86) \ Anaconda \ lib \ site-packages \ sklearn \ utils \ e-packages \ sklearn \ utils \ validation.py", check_array의 453 줄 _assert_all_finite 에있는 "validation.py"44 행 또는 "% r에 비해 너무 큰 값입니다." % X.dtype)

ValueError : 입력에 NaN, 무한대 또는 dtype ('float64')에 비해 너무 큰 값이 들어 있습니다.

내가 읽고있는 파일에 액세스해야하는 경우 링크 할 수 있습니다.

도움 주셔서 감사합니다. ,, 라인 95 :

파일 "/ 사용자/사용자/데스크탑/할당/SQL/파이썬/DA 프로젝트/class17.py C :"

+0

'입력 NaN의 무한대 또는 DTYPE 너무 큰 값 ('float64')가'나는 X_train'과'Y_train''의 내용을 인쇄하고 NaN를 확인하여 시작 했죠을 포함 . 어쩌면'df_subset'는'train_test_split'을 통해 NaN 행을 포함하고 있을지도 모릅니다. 수정 *은'df_subset.dropna (inplace = True)'를 호출 할 수 있습니다. –

+1

감사합니다. df_subset.dropna (inplace = True)를 실행하면 문제가 해결되었습니다. NaN 데이터가있는 2 개의 레코드가있었습니다. –

답변

0

는 여기에주의를 기울여야한다 스택 트레이스의 포인트입니다 (X_train, Y_train)

파일 "D : ₩ Program Files (x86) ₩ Anaconda ₩ lib ₩ site-packages ₩ sklearn ₩ utils ₩ validation.py"44 행 _assert_all_finite "또는 값이 % r에 비해 너무 큽니다. " % X.dtype)

로지스틱 회귀 분석에서 허용하는 X 서식에 문제가 있음을 알 수 있습니다.

X_train 및 X에 잘못된 값이 포함되어 있는지 확인해야합니다.

이 답변은 어떻게하는지 알려줄 것입니다.을 바탕으로

Python pandas: check if any value is NaN in DataFrame