美文网首页
自然语言处理简单应用---预测文章获得的赞同数量

自然语言处理简单应用---预测文章获得的赞同数量

作者: 来个芒果 | 来源:发表于2017-05-16 11:01 被阅读0次

    Hacker News(http://news.ycombinator.com/) 是一个国外新闻社区,用户创造的内容质量远远超出其他创业者主题的网站。

    数据下载地址:https://github.com/arnauddri/hn

    数据集中存储了从HackerNews上爬取的内容,我们的目的是通过对每篇文章的headline进行分析,预测文章获得的赞同数量,数据样例为:



    读取文件

    import pandas as pd
    submissions=pd.read_csv('./data/sel_hn_stories.csv')
    submissions.columns=["submission_time", "upvotes", "url", "headline"]
    submissions = submissions.dropna()
    submissions.head()
    

    对headline进行分词处理:

    tokenized_headlines=[]
    for headline in submissions['headline']:
        tokenized_headlines.append(headline.split(" "))
    
    # 处理tokens:大小写转换、去标点符号,生成unique_words
    punctuation = [",", ":", ";", ".", "'", '"', "’", "?", "/", "-", "+", "&", "(", ")"]
    clean_tokenized = []
    for item in tokenized_headlines:
        tokens=[]
        for token in item:
            token=token.lower()
            for punc in punctuation:
                token.replace(punc,"")
            tokens.append(token)
        clean_tokenized.append(tokens)
    clean_tokenized
    

    清理完以后的样式:

    生成单词矩阵:

    #生成单词矩阵,并对每个headline进行词频统计
    import numpy as np
    
    unique_words=[]
    sigle_words=[]
    for item in clean_tokenized:
        for token in item:
            if token not in sigle_words:
                sigle_words.append(token)
            elif token not in unique_words:
                unique_words.append(token)
    counts=pd.DataFrame(0,index=np.arange(len(clean_tokenized)),columns=unique_words)
    counts.head()
    
    #词频统计
    for i,item in enumerate(clean_tokenized):
        for word in item:
            if word in unique_words:
                counts.iloc[i][word]+=1
    counts.head()
    

    为了提高预测的准确性,我们需要过滤掉出现次数较少的单词、次数较多的单词(如a、an等),这类词对提高预测准确率没有什么帮助。

    # Cleaning dataframe:删除出现频率过多、过少columns
    word_counts=counts.sum(axis=0)
    counts=counts.loc[:,(word_counts>=5)&(word_counts<=100)]
    counts.head()
    

    接下来为预测过程:
    产生训练集、测试集--训练模型--做出预测

    # Split dataset to train and test set
    from sklearn.cross_validation import train_test_split
    
    x_train,x_test,y_train,y_test=train_test_split(counts,submissions['upvotes'],test_size=.2,random_state=1)
    from sklearn.linear_model import LinearRegression
    
    lr=LinearRegression()
    lr.fit(x_train,y_train)
    predictions=lr.predict(x_test)
    
    mse=sum((y_test-predictions)**2)/len(predictions)
    mse
    

    得到mse为:2558.0535509833271
    在我们的数据中,平均赞数为10,标准差为39.5。即便对mse开方,得到的值为46.7,依然偏大。这意味着我们的平均错误为46.7,远远大于标准差,与真实值偏差太大了。
    之所以偏差这么大是因为以下几个原因:

    • 为了方便操作,我使用的数据集仅仅为爬取的文件中的很小一部分,可以尝试使用更多的数据来提高预测性。
    • 尝试增加一些特征:比如标题长度、单词平均长度
    • 尝试使用其他模式,如RandomForest、Ensemble等进行预测,观察模型的性能变化。

    相关文章

      网友评论

          本文标题:自然语言处理简单应用---预测文章获得的赞同数量

          本文链接:https://www.haomeiwen.com/subject/sdtlxxtx.html