def stocGradDescent(self) : """ 计算权重系数向量 """ m, n = weiCount(self.train_vec_list) for j in range(10): dataIndex = range(m)#生成一个长度为1500左右的list for index in range(m) : alpha = 4 / (1.0 + j + index) + 0.01 randIndex = int(random.uniform(0, len(dataIndex))) h = sigmoid(sumArray(self.train_vec_list[randIndex], self.weights)) #print "h:",h, error = self.class_list[randIndex] - h #print "error", error, self.weights = arraySub(self.weights, arrayMulti(alpha, error, self.train_vec_list[randIndex])) del(dataIndex[randIndex]) def weiCount(data_mat) : #返回train_vec_list行数和列数 return len(data_mat), len(data_mat[0])
def sumArray(lineVec, weights) : #两向量的内积 total = 0 for index in range(len(lineVec)) : total += (lineVec[index] * weights[index]) #print "total:", total, return total
def arrayMulti(count, error, lineVec) : for index in range(len(lineVec)) : lineVec[index] = count * error * lineVec[index] return lineVec
def arraySub(weights, lineVec) : for index in range(len(weights)) : weights[index] = weights[index] + lineVec[index] return weights
def makeStopWord(self) : with open("stop_word.txt", "r") as stop_file : self.stop_word = stop_file.read() self.stop_word = self.stop_word.split()
##3.3. 特征词选取的具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
def readEssay(self): """生成特征词集合""" one_block = "" with open("./lily/" + dict_list[0] +".txt", "r") as my_file : line = my_file.read() word_list = list(jieba.cut(line, cut_all = False)) word_dict = {} for word in word_list : if word not in word_dict : word_dict[word] = 1 else : word_dict[word] += 1 word_dict = sorted(word_dict.iteritems(), key = lambda d :d[1], reverse = True) self.feature = [] for word, fre in word_dict : self.feature.append(word) self.feature = self.feature[ : self.dimension] #for word in self.feature : # print word,
def makeVector(self, line) : """将一个帖子的关键词转化成对应的特征向量""" vector = [0] * self.dimension final = [] #去停用词 for word in line : #word = word.encode('utf8') if word not in self.stop_word : final.append(word) #生成特征向量 for word in final : if word in self.feature : vector[self.feature.index(word)] += 1 #print vector return vector