新聞分類問題

2021-09-26 09:54:05 字數 4434 閱讀 1618

import pandas as pd

# 讀取資料

df_news = pd.read_table('./data/val.txt', names=['category', 'theme', 'url', 'content'], encoding='utf-8')

df_news = df_news.dropna()

# print(df_news.shape)

import jieba

content = df_news.content.values.tolist() # 利用tolist將其轉化為列表的形式

# print(content[0])

# 利用jieba進行分詞,並將分好的詞儲存在content_s中

content_s =

for line in content:

current_segment = jieba.lcut(line)

if len(current_segment) > 1 and current_segment != '\r\n':

# print(content_s[1000])

# 建立乙個dataframe格式

df_content = pd.dataframe()

# print(df_content.head())

# 分完詞後資料太亂,對資料進行清洗工作,停用詞過濾操作

stopwords = pd.read_csv('stopwords.txt', index_col=false, sep='\t', quoting=3, names=['stopword'], encoding='utf-8')

# print(stopwords.head())

def drop_stopwords(contents, stopwords):

""":param contents: 輸入分好詞的列表

:param stopwords: 停用詞

:return: 去掉停用詞的contents_clean列表以及用詞雲檢視詞頻視覺化的all_words

"""# 停用詞過濾

contents_clean =

all_words =

for line in contents:

line_clean =

for word in line:

if word in stopwords:

continue

return contents_clean, all_words

contents = df_content.content_s.values.tolist()

stopwords = stopwords.stopword.values.tolist()

contents_clean, all_word = drop_stopwords(contents, stopwords)

df_all_words = pd.dataframe()

# print(df_all_words.head())

df_content = pd.dataframe()

# print(df_content.head())

# 檢視詞頻

import numpy as np

# words_count = df_all_words.groupby(['all_words'])['all_words'].agg()

words_count = df_all_words.groupby(['all_words'])['all_words'].agg(np.size)

words_count = words_count.to_frame()

words_count.columns = ['count']

words_count = words_count.reset_index().sort_values(by=['count'], ascending=false)

# print(words_count.head())

# 利用詞云檢視詞頻

from wordcloud import wordcloud

import matplotlib.pyplot as plt

import matplotlib

matplotlib.rcparams['figure.figsize'] = (100, 50)

wordcloud = wordcloud(font_path = 'data/simhei.ttf', background_color='white', max_font_size=100)

word_freq =

wordcloud = wordcloud.fit_words(word_freq)

plt.imshow(wordcloud)

plt.show()

import jieba.analyse

index = 2000

# print(df_news['content'][index])

content_s_str = ''.join(content_s[index])

# print(' '.join(jieba.analyse.extract_tags(content_s_str, topk=5, withweight=false)))

# lda: 主題模型

from gensim import corpora, models, similarities

import gensim

# 做對映,相當於詞袋

dictionary = corpora.dictionary(contents_clean)

corpus = [dictionary.doc2bow(sentence) for sentence in contents_clean]

lda = gensim.models.ldamodel.ldamodel(corpus=corpus, id2word=dictionary, num_topics=20)

# print(lda.print_topic(1, topn=5))

# 列印20個

# for topic in lda.print_topic(num_topics=20, num_word=5):

# print(topic[1])

# 做分類任務

df_train = pd.dataframe()

# print(df_train.tail())

# print(df_train.label.unique())

# # 對映

# print(df_train.head())

from sklearn.model_selection import train_test_split

# 將資料劃分成訓練集和測試集,這個函式的用途就是講傳入的內容進行隨機劃分

x_train, x_test, y_train, y_test = train_test_split(df_train['contents_clean'].values, df_train['label'].values)

# print(len(x_test))

words =

for line_index in range(len(x_train)):

try:

except:

print(line_index)

# print(line_index, word_index)

print(words[0])

from sklearn.feature_extraction.text import countvectorizer

vec = countvectorizer(analyzer='word', max_features=4000, lowercase=false)

vec.fit(words)

from sklearn.*****_bayes import multinomialnb

classifier = multinomialnb()

classifier.fit(vec.transform(words), y_train)

test_words =

for line_index in range(len(x_test)):

try:

except:

print(line_index)

# print(line_index, word_index)

print(test_words[0])

acc = classifier.score(vec.transform(test_words), y_test) # 算出最終的分類準確度為0.83左右

資料集:

停用詞:

新聞文字分類問題

新聞文字分類問題是典型的字元識別問題。賽題本質是乙個文字分類問題,需要根據每句的字元進行分類。但賽題給出的資料是匿名化的,不能直接使用中文分詞等操作 因此本次賽題的難點是需要對匿名字元進行建模,進而完成文字分類的過程。由於文字資料是一種典型的非結構化資料,因此可能涉及到特徵提取和分類模型兩個部分。思...

文字挖掘之新聞分類

增加序號列 本實驗的資料來源是以單個新聞為單元,需要增加id列來作為每篇新聞的唯一標識,方便下面演算法的計算。分詞及詞頻統計 這兩步都是文字挖掘領域最常規的做法。首先使用分詞元件對content欄位 新聞內容 進行分詞。去除過濾詞之後 過濾詞一般是標點符號及助語 再對詞頻進行統計。停用詞過濾 停用詞...

新聞分類 資料預處理

結構化資料,是可以表示成多行多列的形式,並且,每行 列 都有著具體的含義。非結構化資料,無法合理地表示為多行多列的形式,即使那樣表示,每行 列 也沒有具體的含義。文字資料,是一種非結構化資料,與我們之前分析的結構化資料有所不同。因此,其預處理的步驟與方式也會與結構化資料有所差異。文字資料預處理主要包...