私は、入力されたテキストがSF小説のものかどうかを予測するためにデータセットを訓練しようとしています。私はPythonには比較的新しいので、私が間違っていることを正確には知らない。データフレームを使用したデータモデリング
コード:
#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)¥Program Files(x86)¥Anaconda¥lib¥site-packages¥sklearn¥linear_model¥logistic.py "、行1216、適合 オーダー=" C ")
ファイル" D: \アナコンダ\ libには\サイト・パッケージに\ sklearn \ utilsの\ validation.py "check_X_y ensure_min_features、warn_on_dtype、推定)
ファイルの行573、" D:\プログラムファイル(x86の)\アナコンダ\ libに\座ります(配列)
ファイル "D:¥Program Files(x86)¥Anaconda¥lib¥site-packages¥sklearn¥utils¥e-packages¥sklearn¥utils¥validation.py"、行453、check_array \ _assert_all_finite の "validation.py"、行44、または%rの値が大きすぎます。 " %X.dtype)
ValueError:入力にNaN、無限大またはdtype( 'float64')には大きすぎる値が含まれています。
私が読んでいるファイルにアクセスする必要がある場合は、それらをリンクすることができます。
ありがとうございました!ここで
がNaN、無限大またはDTYPEのためにあまりにも大きな値(「のfloat64」)を'含まれている、私は 'X_train'と' Y_train'の内容を印刷し、NaNのためにチェックすることで起動したいです。たぶん 'df_subset'には、' train_test_split'によってNaNの行がいくつか含まれているかもしれません。修正*は、 'df_subset.dropna(inplace = True)'を呼び出すかもしれません。 –
ありがとう、df_subset.dropna(inplace = True)を実行すると問題が解決しました。 NaNデータを持つ2つのレコードがありました。 –