一个基于概率统计的N-Gram模型(取N=2的Bigram模型作为示例),这是最轻量级的"预测"类模型,仅需几十行代码即可实现。Bigram模型是一种基于统计的语言模型。它假设一个词的出现概率仅依赖于它前面的一个词。通过统计大规模语料中每个词对(即bigram)出现的频率,来估算词的条件概率。在文本生成、语音识别等任务中,可依据此模型预测下一个可能出现的词。
本模型基于N-Gram概率统计原理,核心思想是"词语序列的概率预测"。设计分为三阶段:
该设计无需神经网络,仅依赖词共现统计,实现毫秒级训练预测,特别适合小规模场景的简单语义建模。
from collections import defaultdict, Counter
import random
class SimpleProphet:
def __init__(self):
self.model = defaultdict(Counter) # 存储词与后继词频的映射
def train(self, text):
"""训练模型:统计词序列概率"""
words = text.split()
for i in range(len(words)-1):
current, next_word = words[i], words[i+1]
self.model[current][next_word] += 1 # 记录当前词到下一个词的转移频次
def predict_next(self, current_word):
"""预测下一个词"""
if current_word not in self.model:
return None
options = self.model[current_word]
total = sum(options.values())
# 按概率随机选择(核心预测逻辑)
return random.choices(
list(options.keys()),
weights=list(options.values())
)[0]
def generate(self, start, length=5):
"""生成预测序列"""
result = [start]
for _ in range(length-1):
next_word = self.predict_next(result[-1])
if not next_word: break
result.append(next_word)
return " ".join(result)
假设您是电商运营,需要批量生成手机配件名称
# 准备训练数据(真实场景需更大数据集)
training_data = """
手机钢化膜 防蓝光 华为专用 抗摔
手机壳 磨砂 苹果15 透明 防刮
充电器 快充 30W Type-C 折叠
数据线 编织 1米 快充 耐用
"""
prophet = SimpleProphet()
prophet.train(training_data)
# 案例1:基于"手机"生成名称
print(prophet.generate("手机", 3))
# 示例输出:手机钢化膜 防蓝光
# 案例2:基于"充电器"生成名称
print(prophet.generate("充电器", 4))
# 示例输出:充电器快充 30W Type-C
# 修改训练数据为商品描述
desc_data = """
高清透光 防指纹 易安装 9H硬度
亲肤手感 精准孔位 轻薄不发黄
智能温控 多重保护 小巧便携
尼龙编织 抗氧化 弯头设计
"""
prophet.train(desc_data)
print(prophet.generate("智能", 2)) # 输出:智能温控
print(prophet.generate("亲肤", 3)) # 输出:亲肤手感 精准孔位
def predict_next_smoothed(self, current_word):
options = self.model.get(current_word, {})
all_words = set(word for words in self.model.values() for word in words)
# Laplace平滑处理
return random.choices(
list(all_words) if not options else list(options.keys()),
weights=[options.get(w, 1) for w in all_words] # 未出现词给默认频次1
)[0]
关键特点:无需GPU/仅依赖基础概率统计/训练预测在毫秒级完成。实际应用中,增加训练数据量可显著提升效果,百条数据即可获得实用结果。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。