读取文本数据,并计算特征向量

numpy.linalg.eig() 计算矩阵特征向量

import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
from numpy import linalg as LA

fcf = glob.glob('data/*.txt')

#get the feature
file_feature = open('data/feature.txt', 'r')
Feature = file_feature.read().split()
file_feature.close()

total_files = len(fcf)-1
total_keywords = len(Feature)
Xtrain = np.zeros([40,total_keywords]) 
for i in range(40):
	file = open(fcf[i], 'r',errors = "replace")
	test = file.read()
	file.close()
	for j in range(total_keywords):
		#cout the number of ketword
		occurence = test.count(Feature[j])
		Xtrain[i][j] = occurence

Xtest = np.zeros([10,total_keywords])
for i in range(41, 51):
	file = open(fcf[i], 'r',errors = "replace")
	test = file.read()
	file.close()
	for j in range(total_keywords):
		#cout the number of ketword
		occurence = test.count(Feature[j])
		Xtest[i-41][j] = occurence


meanXtrain = np.mean(Xtrain,axis = 0)
Ctrx = Xtrain - meanXtrain
S1 = np.dot(np.transpose(Ctrx),Ctrx)
Cxx = 1.0/(Xtrain.shape[0]-1)*S1
W, V = LA.eig(Cxx)#W-特征值, V-特征向量
print(V)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Python中,我们可以使用诸如Scikit-learn等库来将文本转换为特征向量。具体骤如下: 1. 读取数据:从文本文件或数据库中读取文本数据。 2. 文本预处理:对文本进行清洗、分词等操作,例如去除停用词、标点符号、数字等。 3. 特征抽取:将文本转换为数值特征向量。通常有两种方法: - 统计向量:根据文本中每个词出现的频率构建一个向量,其中每个元素表示一个词在文本中出现的次数或频率。常见的统计向量包括词频(TF)和词频-逆文档频率(TF-IDF)向量。 - 嵌入向量:使用神经网络等模型将文本映射到稠密的低维向量空间中。常见的嵌入向量包括Word2Vec、FastText等。 4. 特征选择:根据特征的重要性选择最具代表性的特征。 下面是一个使用Scikit-learn库将文本转换为TF-IDF向量的示例代码: ``` from sklearn.feature_extraction.text import TfidfVectorizer # 读取文本数据 corpus = ['This is the first document.', 'This is the second document.', 'And this is the third one.', 'Is this the first document?'] # 创建TfidfVectorizer对象 vectorizer = TfidfVectorizer() # 计算TF-IDF向量 X = vectorizer.fit_transform(corpus) # 查看词汇表 print(vectorizer.get_feature_names()) # 查看文本向量 print(X.toarray()) ``` 运行结果: ``` ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this'] [[0. 0.43877674 0.55847784 0.43877674 0. 0. 0.43877674 0. 0.43877674] [0. 0.43877674 0. 0.43877674 0. 0.70710678 0.43877674 0. 0.43877674] [0.5 0. 0. 0.5 0.5 0. 0.5 0.5 0. ] [0. 0.43877674 0.55847784 0.43877674 0. 0. 0.43877674 0. 0.43877674]] ``` 可以看到,该代码将4个文本数据转换为一个4x9的TF-IDF矩阵,其中每行是一个文本的TF-IDF向量,每列是一个词的TF-IDF值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值