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

相关文章

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

Java Lettuce 客户端入门到生产的实现步骤

《JavaLettuce客户端入门到生产的实现步骤》本文主要介绍了JavaLettuce客户端入门到生产的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录1 安装依赖MavenGradle2 最小化连接示例3 核心特性速览4 生产环境配置建议5 常见问题

使用python生成固定格式序号的方法详解

《使用python生成固定格式序号的方法详解》这篇文章主要为大家详细介绍了如何使用python生成固定格式序号,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录生成结果验证完整生成代码扩展说明1. 保存到文本文件2. 转换为jsON格式3. 处理特殊序号格式(如带圈数字)4

linux ssh如何实现增加访问端口

《linuxssh如何实现增加访问端口》Linux中SSH默认使用22端口,为了增强安全性或满足特定需求,可以通过修改SSH配置来增加或更改SSH访问端口,具体步骤包括修改SSH配置文件、增加或修改... 目录1. 修改 SSH 配置文件2. 增加或修改端口3. 保存并退出编辑器4. 更新防火墙规则使用uf

Java 的ArrayList集合底层实现与最佳实践

《Java的ArrayList集合底层实现与最佳实践》本文主要介绍了Java的ArrayList集合类的核心概念、底层实现、关键成员变量、初始化机制、容量演变、扩容机制、性能分析、核心方法源码解析、... 目录1. 核心概念与底层实现1.1 ArrayList 的本质1.1.1 底层数据结构JDK 1.7

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关