|
||||
0001 # 0002 # Licensed to the Apache Software Foundation (ASF) under one or more 0003 # contributor license agreements. See the NOTICE file distributed with 0004 # this work for additional information regarding copyright ownership. 0005 # The ASF licenses this file to You under the Apache License, Version 2.0 0006 # (the "License"); you may not use this file except in compliance with 0007 # the License. You may obtain a copy of the License at 0008 # 0009 # http://www.apache.org/licenses/LICENSE-2.0 0010 # 0011 # Unless required by applicable law or agreed to in writing, software 0012 # distributed under the License is distributed on an "AS IS" BASIS, 0013 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 0014 # See the License for the specific language governing permissions and 0015 # limitations under the License. 0016 # 0017 0018 from __future__ import print_function 0019 0020 from pyspark import SparkContext 0021 # $example on$ 0022 from pyspark.mllib.feature import HashingTF, IDF 0023 # $example off$ 0024 0025 if __name__ == "__main__": 0026 sc = SparkContext(appName="TFIDFExample") # SparkContext 0027 0028 # $example on$ 0029 # Load documents (one per line). 0030 documents = sc.textFile("data/mllib/kmeans_data.txt").map(lambda line: line.split(" ")) 0031 0032 hashingTF = HashingTF() 0033 tf = hashingTF.transform(documents) 0034 0035 # While applying HashingTF only needs a single pass to the data, applying IDF needs two passes: 0036 # First to compute the IDF vector and second to scale the term frequencies by IDF. 0037 tf.cache() 0038 idf = IDF().fit(tf) 0039 tfidf = idf.transform(tf) 0040 0041 # spark.mllib's IDF implementation provides an option for ignoring terms 0042 # which occur in less than a minimum number of documents. 0043 # In such cases, the IDF for these terms is set to 0. 0044 # This feature can be used by passing the minDocFreq value to the IDF constructor. 0045 idfIgnore = IDF(minDocFreq=2).fit(tf) 0046 tfidfIgnore = idfIgnore.transform(tf) 0047 # $example off$ 0048 0049 print("tfidf:") 0050 for each in tfidf.collect(): 0051 print(each) 0052 0053 print("tfidfIgnore:") 0054 for each in tfidfIgnore.collect(): 0055 print(each) 0056 0057 sc.stop()
[ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
This page was automatically generated by the 2.1.0 LXR engine. The LXR team |