想知道usaco是什么比赛?

Python07

想知道usaco是什么比赛?,第1张

USACO竞赛指的是美国计算机奥林匹克竞赛。是一项为高中生或者年龄更小的学员提供的在线竞赛,旨在锻炼学员用计算机编程解决问题的能力。它的全称是USA Computing Olympiad。竞赛在家里通过网上进行。

与其它竞赛不同,USACO没有学校和地区级的限制,任何学员都可以通过互联网参加。这项赛事不仅可以培养孩子的编程思维,好的竞赛成绩还能给孩子大学申请加分。有些编程题跟谷歌,脸书等顶级科技公司面试题类似,对孩子以后申请实习也大有裨益。

USACO 接受多种语言的解决方案,包括 C++,C,Java 和 Python。由于Java 和 Python 相比于 C++/C 语言运行得会慢一些,所以这两种语言所允许的运行时间是 C++ 和 C 的两倍。相比于国内 NOIP 只接受 C++ 作为考试语言,USACO 提供了更加灵活的支持,使得比较喜欢 Java 和 Python 的人也有机会参与到算法竞赛中。

向量(word2vec)原始的代码是C写的,python也有对应的版本,被集成在一个非常牛逼的框架gensim中。

我在自己的开源语义网络项目graph-mind(其实是我自己写的小玩具)中使用了这些功能,大家可以直接用我在上面做的进一步的封装傻瓜式地完成一些操作,下面分享调用方法和一些code上的心得。

1.一些类成员变量:

[python] view plain copy

def __init__(self, modelPath, _size=100, _window=5, _minCount=1, _workers=multiprocessing.cpu_count()):

self.modelPath = modelPath

self._size = _size

self._window = _window

self._minCount = _minCount

self._workers = _workers

modelPath是word2vec训练模型的磁盘存储文件(model在内存中总是不踏实),_size是词向量的维度,_window是词向量训练时的上下文扫描窗口大小,后面那个不知道,按默认来,_workers是训练的进程数(需要更精准的解释,请指正),默认是当前运行机器的处理器核数。这些参数先记住就可以了。

2.初始化并首次训练word2vec模型

完成这个功能的核心函数是initTrainWord2VecModel,传入两个参数:corpusFilePath和safe_model,分别代表训练语料的路径和是否选择“安全模式”进行初次训练。关于这个“安全模式”后面会讲,先看代码:

[python] view plain copy

def initTrainWord2VecModel(self, corpusFilePath, safe_model=False):

'''''

init and train a new w2v model

(corpusFilePath can be a path of corpus file or directory or a file directly, in some time it can be sentences directly

about soft_model:

if safe_model is true, the process of training uses update way to refresh model,

and this can keep the usage of os's memory safe but slowly.

and if safe_model is false, the process of training uses the way that load all

corpus lines into a sentences list and train them one time.)

'''

extraSegOpt().reLoadEncoding()

fileType = localFileOptUnit.checkFileState(corpusFilePath)

if fileType == u'error':

warnings.warn('load file error!')

return None

else:

model = None

if fileType == u'opened':

print('training model from singleFile!')

model = Word2Vec(LineSentence(corpusFilePath), size=self._size, window=self._window, min_count=self._minCount, workers=self._workers)

elif fileType == u'file':

corpusFile = open(corpusFilePath, u'r')

print('training model from singleFile!')

model = Word2Vec(LineSentence(corpusFile), size=self._size, window=self._window, min_count=self._minCount, workers=self._workers)

elif fileType == u'directory':

corpusFiles = localFileOptUnit.listAllFileInDirectory(corpusFilePath)

print('training model from listFiles of directory!')

if safe_model == True:

model = Word2Vec(LineSentence(corpusFiles[0]), size=self._size, window=self._window, min_count=self._minCount, workers=self._workers)

for file in corpusFiles[1:len(corpusFiles)]:

model = self.updateW2VModelUnit(model, file)

else:

sentences = self.loadSetencesFromFiles(corpusFiles)

model = Word2Vec(sentences, size=self._size, window=self._window, min_count=self._minCount, workers=self._workers)

elif fileType == u'other':

# TODO add sentences list directly

pass

model.save(self.modelPath)

model.init_sims()

print('producing word2vec model ... ok!')

return model

首先是一些杂七杂八的,判断一下输入文件路径下访问结果的类型,根据不同的类型做出不同的文件处理反应,这个大家应该能看懂,以corpusFilePath为一个已经打开的file对象为例,创建word2vec model的代码为:

[python] view plain copy

model = Word2Vec(LineSentence(corpusFilePath), size=self._size, window=self._window, min_count=self._minCount, workers=self._workers)

其实就是这么简单,但是为了代码健壮一些,就变成了上面那么长。问题是在面对一个路径下的许多训练文档且数目巨大的时候,一次性载入内存可能不太靠谱了(没有细研究gensim在Word2Vec构造方法中有没有考虑这个问题,只是一种习惯性的警惕),于是我设定了一个参数safe_model用于判断初始训练是否开启“安全模式”,所谓安全模式,就是最初只载入一篇语料的内容,后面的初始训练文档通过增量式学习的方式,更新到原先的model中。

上面的代码里,corpusFilePath可以传入一个已经打开的file对象,或是一个单个文件的地址,或一个文件夹的路径,通过函数checkFileState已经做了类型的判断。另外一个函数是updateW2VModelUnit,用于增量式训练更新w2v的model,下面会具体介绍。loadSetencesFromFiles函数用于载入一个文件夹中全部语料的所有句子,这个在源代码里有,很简单,哥就不多说了。

3.增量式训练更新word2vec模型

增量式训练w2v模型,上面提到了一个这么做的原因:避免把全部的训练语料一次性载入到内存中。另一个原因是为了应对语料随时增加的情况。gensim当然给出了这样的solution,调用如下:

[python] view plain copy

def updateW2VModelUnit(self, model, corpusSingleFilePath):

'''''

(only can be a singleFile)

'''

fileType = localFileOptUnit.checkFileState(corpusSingleFilePath)

if fileType == u'directory':

warnings.warn('can not deal a directory!')

return model

if fileType == u'opened':

trainedWordCount = model.train(LineSentence(corpusSingleFilePath))

print('update model, update words num is: ' + trainedWordCount)

elif fileType == u'file':

corpusSingleFile = open(corpusSingleFilePath, u'r')

trainedWordCount = model.train(LineSentence(corpusSingleFile))

print('update model, update words num is: ' + trainedWordCount)

else:

# TODO add sentences list directly (same as last function)

pass

return model

简单检查文件type之后,调用model对象的train方法就可以实现对model的更新,这个方法传入的是新语料的sentences,会返回模型中新增词汇的数量。函数全部执行完后,return更新后的model,源代码中在这个函数下面有能够处理多类文件参数(同2)的增强方法,这里就不多介绍了。

4.各种基础查询

当你确定model已经训练完成,不会再更新的时候,可以对model进行锁定,并且据说是预载了相似度矩阵能够提高后面的查询速度,但是你的model从此以后就read only了。

[python] view plain copy

def finishTrainModel(self, modelFilePath=None):

'''''

warning: after this, the model is read-only (can't be update)

'''

if modelFilePath == None:

modelFilePath = self.modelPath

model = self.loadModelfromFile(modelFilePath)

model.init_sims(replace=True)

可以看到,所谓的锁定模型方法,就是init_sims,并且把里面的replace参数设定为True。

然后是一些word2vec模型的查询方法:

[python] view plain copy

def getWordVec(self, model, wordStr):

'''''

get the word's vector as arrayList type from w2v model

'''

return model[wordStr]

[python] view plain copy

def queryMostSimilarWordVec(self, model, wordStr, topN=20):

'''''

MSimilar words basic query function

return 2-dim List [0] is word [1] is double-prob

'''

similarPairList = model.most_similar(wordStr.decode('utf-8'), topn=topN)

return similarPairList

[python] view plain copy

def culSimBtwWordVecs(self, model, wordStr1, wordStr2):

'''''

two words similar basic query function

return double-prob

'''

similarValue = model.similarity(wordStr1.decode('utf-8'), wordStr2.decode('utf-8'))

return similarValue

上述方法都很简单,基本上一行解决,在源代码中,各个函数下面依然是配套了相应的model文件处理版的函数。其中,getWordVec是得到查询词的word2vec词向量本身,打印出来是一个纯数字的array;queryMostSimilarWordVec是得到与查询词关联度最高的N个词以及对应的相似度,返回是一个二维list(注释里面写的蛮清楚);culSimBtwWordVecs是得到两个给定词的相似度值,直接返回double值。

5.Word2Vec词向量的计算

研究过w2v理论的童鞋肯定知道词向量是可以做加减计算的,基于这个性质,gensim给出了相应的方法,调用如下:

[python] view plain copy

def queryMSimilarVecswithPosNeg(self, model, posWordStrList, negWordStrList, topN=20):

'''''

pos-neg MSimilar words basic query function

return 2-dim List [0] is word [1] is double-prob

'''

posWordList = []

negWordList = []

for wordStr in posWordStrList:

posWordList.append(wordStr.decode('utf-8'))

for wordStr in negWordStrList:

negWordList.append(wordStr.decode('utf-8'))

pnSimilarPairList = model.most_similar(positive=posWordList, negative=negWordList, topn=topN)

return pnSimilarPairList

由于用的是py27,所以之前对传入的词列表数据进行编码过滤,这里面posWordList可以认为是对结果产生正能量的词集,negWordList则是对结果产生负能量的词集,同时送入most_similar方法,在设定return答案的topN,得到的返回结果形式同4中的queryMostSimilarWordVec函数,大家可以这样数学地理解这个操作:

下面一个操作是我自创的,假设我想用上面词向量topN“词-关联度”的形式展现两个词或两组词之间的关联,我是这么做的:

[python] view plain copy

def copeMSimilarVecsbtwWordLists(self, model, wordStrList1, wordStrList2, topN_rev=20, topN=20):

'''''

range word vec res for two wordList from source to target

use wordVector to express the relationship between src-wordList and tag-wordList

first, use the tag-wordList as neg-wordList to get the rev-wordList,

then use the scr-wordList and the rev-wordList as the new src-tag-wordList

topN_rev is topN of rev-wordList and topN is the final topN of relationship vec

'''

srcWordList = []

tagWordList = []

srcWordList.extend(wordStr.decode('utf-8') for wordStr in wordStrList1)

tagWordList.extend(wordStr.decode('utf-8') for wordStr in wordStrList2)

revSimilarPairList = self.queryMSimilarVecswithPosNeg(model, [], tagWordList, topN_rev)

revWordList = []

revWordList.extend(pair[0].decode('utf-8') for pair in revSimilarPairList)

stSimilarPairList = self.queryMSimilarVecswithPosNeg(model, srcWordList, revWordList, topN)

return stSimilarPairList

这个操作的思路就是,首先用两组词中的一组作为negWordList,传入上面的queryMSimilarVecswithPosNeg函数,得到topN一组的中转词,在使用这些中转词与原先的另一组词进行queryMSimilarVecswithPosNeg操作,很容易理解,第一步得到的是一组词作为negWordList的反向结果,再通过这个反向结果与另一组词得到“负负得正”的效果。这样就可以通过一组topN的“词-关联度”配对List表示两组词之间的关系。