记写word2vec问题汇总

1.编码问题

代码:

def read_data(filename):#解压下载的压缩文件 
    #with zipfile.ZipFile(filename) as f:
    data=[]
    f=open(filename,"r")
    for line in f:
        line=line.strip("\n")
        data.append(jieba.lcut(line,False))#将数据转成单词列表
    #data=tf.compat.as_str(list(jieba.cut(f)))
    return data

出现问题:

网上搜索后有人说是加编码

于是改成

f=open(filename,"r",encoding='UTF-8')

就能正确读取了。

2.AttributeError: 'str' object has no attribute 'decode'

好像是pyhton2和python3语法的原因

3.TypeError: unhashable type: 'list'

出问题的代码:

def build_dataset(words):
    count=[['UNK',-1]]
    count.extend(collections.Counter(words).most_common(vocabulary_size-1))#统计单词频数
    dictionary=dict()#top5000存入dictionary
    for word,_ in count:#将单词转换为频数的编号 
        dictionary[word]=len(dictionary)
    data=list()
    unk_count=0
    for word in words:
        if word in dictionary:
            index = dictionary[word]
        else:#没出现在dictionary中编号为零 定为unknown
            index=0
            unk_count+=1
        data.append(index)
    count[0][1]=unk_count
    reverse_dictionary=dict(zip(dictionary.values(),dictionary.keys()))
    return data,count,dictionary,reverse_dictionary#转换后编码、每个单词频数统计、词汇表、反转形式

查了一下各函数的用法

collections.Counter(word)

返回word中各个元素的个数

from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print (c)
print(dict(c))

输出:
Counter({'blue': 3, 'red': 2, 'green': 1})
{'red': 2, 'blue': 3, 'green': 1}

most_common(n)

返回top-n的元素

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print (c.most_common(2))

输出
[('blue', 3), ('red', 2)]

经过一番排查之后发现原来是我自己在存放word时出错了

data.append(jieba.lcut(line,False))#将数据转成单词列表

这里用append,data列表中添加的新元素是每一句话经过分词之后形成的列表,也就是说添加的是列表变量

改成extend()就好了,添加的是列表里的元素

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值