python实现fasttext

2023-12-01 14:28
文章标签 python 实现 fasttext

本文主要是介绍python实现fasttext,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、用开源库

import fasttext# 准备训练数据
# 数据应该是一个文本文件,其中每一行表示一个样本,每行以一个标签开头,然后是文本内容。
# 标签的格式为:__label__<your-label>,例如:__label__positive I love this movie!train_data = 'path/to/your/training/data.txt'# 训练模型
model = fasttext.train_supervised(train_data)# 保存模型
model.save_model('fasttext_model.bin')# 加载模型
model = fasttext.load_model('fasttext_model.bin')# 使用模型进行预测
text = 'This is an example sentence.'
prediction = model.predict(text)print(f'Text: {text}')
print(f'Prediction: {prediction}')# 计算模型在测试数据上的精度
test_data = 'path/to/your/test/data.txt'
result = model.test(test_data)print(f'Precision: {result[1]}')
print(f'Recall: {result[2]}')

2、用TensorFlow

import tensorflow as tf
import numpy as np
import re
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_reportdef tokenize(text):return re.findall(r'\w+', text.lower())def preprocess_data(data):sentences = []labels = []for line in data:label, text = line.split(' ', 1)sentences.append(tokenize(text))labels.append(label)return sentences, labelsdef build_vocab(sentences, min_count=5):word_counts = defaultdict(int)for sentence in sentences:for word in sentence:word_counts[word] += 1vocab = {word: idx for idx, (word, count) in enumerate(word_counts.items()) if count >= min_count}return vocabdef sentence_to_vector(sentence, vocab):vector = np.zeros(len(vocab))for word in sentence:if word in vocab:vector[vocab[word]] += 1return vector# 示例数据
data = ["__label__positive I love this movie!","__label__negative This movie is terrible!","__label__positive This is a great film.","__label__negative I didn't enjoy the movie."
]sentences, labels = preprocess_data(data)
vocab = build_vocab(sentences)
label_encoder = LabelEncoder().fit(labels)X = np.array([sentence_to_vector(sentence, vocab) for sentence in sentences])
y = label_encoder.transform(labels)# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 创建模型
model = tf.keras.Sequential([tf.keras.layers.Dense(len(set(labels)), input_shape=(len(vocab),), activation='softmax')
])# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 训练模型
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test))# 预测
test_sentence = "This is an amazing movie!"
prediction = model.predict(np.array([sentence_to_vector(tokenize(test_sentence), vocab)]))
predicted_label = label_encoder.inverse_transform([np.argmax(prediction)])
print(f'Text: {test_sentence}')
print(f'Prediction: {predicted_label}')# 评估
y_pred = model.predict(X_test)
y_pred = label_encoder.inverse_transform(np.argmax(y_pred, axis=1))
y_true = label_encoder.inverse_transform(y_test)
print(classification_report(y_true, y_pred))

3、用python实现

import numpy as np
import re
from collections import defaultdict
from sklearn.preprocessing import normalize
from sklearn.metrics import classification_reportdef tokenize(text):return re.findall(r'\w+', text.lower())def preprocess_data(data):sentences = []labels = []for line in data:label, text = line.split(' ', 1)sentences.append(tokenize(text))labels.append(label)return sentences, labelsdef build_vocab(sentences, min_count=5):word_counts = defaultdict(int)for sentence in sentences:for word in sentence:word_counts[word] += 1vocab = {word: idx for idx, (word, count) in enumerate(word_counts.items()) if count >= min_count}return vocabdef build_label_index(labels):label_index = {}for label in labels:if label not in label_index:label_index[label] = len(label_index)return label_indexdef sentence_to_vector(sentence, vocab):vector = np.zeros(len(vocab))for word in sentence:if word in vocab:vector[vocab[word]] += 1return vectordef train_fasttext(sentences, labels, vocab, label_index, lr=0.01, epochs=10):W = np.random.randn(len(label_index), len(vocab))for epoch in range(epochs):for sentence, label in zip(sentences, labels):vector = sentence_to_vector(sentence, vocab)scores = W.dot(vector)probs = np.exp(scores) / np.sum(np.exp(scores))target = np.zeros(len(label_index))target[label_index[label]] = 1W -= lr * np.outer(probs - target, vector)return Wdef predict_fasttext(sentence, W, vocab, label_index):vector = sentence_to_vector(sentence, vocab)scores = W.dot(vector)probs = np.exp(scores) / np.sum(np.exp(scores))max_index = np.argmax(probs)return list(label_index.keys())[list(label_index.values()).index(max_index)]# 示例数据
data = ["__label__positive I love this movie!","__label__negative This movie is terrible!","__label__positive This is a great film.","__label__negative I didn't enjoy the movie."
]sentences, labels = preprocess_data(data)
vocab = build_vocab(sentences)
label_index = build_label_index(labels)# 训练模型
W = train_fasttext(sentences, labels, vocab, label_index)# 预测
test_sentence = "This is an amazing movie!"
prediction = predict_fasttext(tokenize(test_sentence), W, vocab, label_index)
print(f'Text: {test_sentence}')
print(f'Prediction: {prediction}')# 评估
y_true = labels
y_pred = [predict_fasttext(sentence, W, vocab, label_index) for sentence in sentences]
print(classification_report(y_true, y_pred))

这篇关于python实现fasttext的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/441514

相关文章

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e