Hoey笔记

和有趣的人做尽有趣的事


  • Home

  • Archives

  • Sitemap

  • Search

HuggingFace Embedding的模型提取

Posted on 2025-06-25

提取huggingface上关于embedding的模型 – 20250625

以下内容借助AI提取,仅做参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
[Qwen/Qwen3-Embedding-0.6B]: 解决问题:[将文本转换为向量表示问题] 
[Qwen/Qwen3-Embedding-8B]: 解决问题:[文本向量化及语义表征问题]
[Qwen/Qwen3-Embedding-4B]: 解决问题:将文本转换为向量表示用于下游任务
[jinaai/jina-embeddings-v3]: 解决问题:文本向量化及语义相似度计算
Qwen/Qwen3-Embedding-0.6B-GGUF: 解决问题:将文本转换为向量表示
jinaai/jina-embeddings-v4: 解决问题:文本特征提取与语义表示
[Qwen/Qwen3-Embedding-8B-GGUF]: 解决问题:文本向量化以用于下游任务
[Qwen/Qwen3-Embedding-4B-GGUF]: 解决问题:文本特征提取与向量化表示
ai-sage/Giga-Embeddings-instruct: 解决问题:文本向量化以用于多种NLP任务
boboliu/Qwen3-Embedding-0.6B-W4A16-G128: 解决问题:文本向量化及语义表示问题
[pyannote/embedding]: 解决问题:语音特征嵌入表示相关问题
NeuML/pubmedbert-base-embeddings: 解决问题:处理生物医学文本特征表示
desarrolloasesoreslocales/jina-embeddings-v2-base-en-finetuned-legalcorpus: 解决问题:处理英文法律文本嵌入问题
maidlun1020/bce-embedding-base_v1: 解决问题:未找到该模型: 解决问题的相关信息
[jinaai/jina-embeddings-v2-base-zh]: 解决问题:中文文本向量化表示问题
[jinaai/jina-embeddings-v2-base-de]: 解决问题:德语文本嵌入表示问题
Marqo/marqo-ecommerce-embeddings-L: 解决问题:电商领域文本特征嵌入问题
ibm-granite/granite-embedding-30m-english: 解决问题:英文文本向量化及语义表示问题
ibm-granite/granite-embedding-107m-multilingual: 解决问题:多语言文本嵌入表示问题
Salesforce/SFR-Embedding-Code-2B_R: 解决问题:代码相关的嵌入表示问题
alikia2x/jina-embedding-v3-m2v-256: 解决问题:文本到向量的嵌入表示问题
[AhmedZaky1/DIMI-embedding-sts-matryoshka]: 解决问题:语义文本相似度计算问题
onnx-community/Qwen3-Embedding-0.6B-ONNX: 解决问题:文本向量化及语义特征提取
electroglyph/Qwen3-Embedding-0.6B-onnx-uint8: 解决问题:将文本转换为向量表示
annamodels/LGAI-Embedding-Preview: 解决问题:未找到该模型: 解决问题相关信息
[C10X/Qwen3-Embedding-TurboX]: 解决问题:文本特征提取与语义表示问题
[janni-t/qwen3-embedding-0.6b-tei-onnx]: 解决问题:文本向量化及语义表示问题
itsbohara/qwen3_embedding_4b_q8_0: 解决问题:文本向量化及语义表示问题
MALIBA-AI/bambara-embeddings: 解决问题:生成班巴拉语的词嵌入表示
malcolmrey/embeddings: 解决问题:未找到该模型明确解决的问题信息
flax-sentence-embeddings/multi-qa_v1-distilbert-cls_dot: 解决问题:多语言问答文本嵌入表示问题
flax-sentence-embeddings/multi-qa_v1-distilbert-mean_cos: 解决问题:多语言问答任务语义匹配
flax-sentence-embeddings/multi-qa_v1-mpnet-cls_dot: 解决问题:多语言问答文本嵌入问题
flax-sentence-embeddings/multi-qa_v1-mpnet-mean_cos: 解决问题:多语言问答句嵌入表示问题
[flax-sentence-embeddings/reddit_single-context_mpnet-base]: 解决问题:处理Reddit文本单上下文嵌入问题
[flax-sentence-embeddings/st-codesearch-distilroberta-base]: 解决问题:[代码搜索相关语义匹配问题]
flax-sentence-embeddings/stackoverflow_mpnet-base: 解决问题:处理Stack Overflow文本语义表示
[sentence-transformers/average_word_embeddings_glove.6B.300d]: 解决问题:将文本转换为词嵌入向量表示
sentence-transformers/average_word_embeddings_glove.840B.300d: 解决问题:将文本转换为固定长度向量表示
[sentence-transformers/average_word_embeddings_komninos]: 解决问题:生成句子嵌入用于语义表示
[sentence-transformers/average_word_embeddings_levy_dependency]: 解决问题:生成句子的平均词嵌入表示
[MrAnderson/bert-base-1024-full-trivia-copied-embeddings]: 解决问题:[处理问答类琐事相关任务]
MrAnderson/nystrom-2048-full-trivia-copied-embeddings: 解决问题:处理琐事相关的嵌入表示问题
MrAnderson/yoso-2048-full-trivia-copied-embeddings: 解决问题:未找到相关信息,无法明确: 解决问题。
MrAnderson/yoso-512-full-trivia-copied-embeddings: 解决问题:处理问答琐事相关嵌入表示
MrAnderson/bert-base-2048-full-trivia-copied-embeddings: 解决问题:处理问答类琐事信息嵌入问题
MrAnderson/nystrom-1024-full-trivia-copied-embeddings: 解决问题:处理与琐事相关的嵌入表示问题
Kalaoke/embeddings_dense_model: 解决问题:暂未找到该模型: 解决问题的相关信息
MrAnderson/nystrom-4096-full-trivia-copied-embeddings: 解决问题:处理琐事相关的嵌入表示问题
MrAnderson/bert-base-4096-full-trivia-copied-embeddings: 解决问题:可能用于问答类知识相关嵌入表示
jwieting/simple-paraphrastic-embeddings: 解决问题:生成句子的释义嵌入表示
[shiemn/bigdatageo-gelectra-base-new-embeddings]: 解决问题:可能用于地理相关数据嵌入表示
[ITESM/sentece-embeddings-BETO]: 解决问题:生成西班牙语句子的嵌入表示
[espejelomar/sentece-embeddings-BETO]: 解决问题:生成西班牙语句子的嵌入表示
cambridgeltl/tweet-roberta-base-embeddings-v1: 解决问题:将推文转换为向量表示
sumedh/pretrained-word-embeddings: 解决问题:将单词转换为向量表示
florentgbelidji/blip_image_embeddings: 解决问题:将图像转换为向量嵌入表示
philschmid/all-MiniLM-L6-v2-optimum-embeddings: 解决问题:文本语义表示与相似度计算
crumb/ViT-L-14-Token-Embeddings: 解决问题:图像视觉特征的嵌入表示问题
ProGamerGov/knollingcase-embeddings-sd-v2-0: 解决问题:生成特定风格图像嵌入表示
mikumikugeek/embeddings: 解决问题:未找到该模型: 解决问题的相关信息
soknife/embeddings: 解决问题:暂未获取到该模型: 解决问题相关信息。
KnutJaegersberg/sentence_transformer_mpnet_v2_to_kg_embeddings_wikidata5m: 解决问题:将句子转换为知识图谱嵌入
ProGamerGov/winter-cat-embeddings-sd-v2-1: 解决问题:用于StableDiffusion生成特定风格图像
rickysambora55/ai-embeddings: 解决问题:未找到该模型相关有效: 解决问题信息
SirVeggie/nixeu_embeddings: 解决问题:未在huggingface找到相关: 解决问题信息
Priyanshu9991/sd2.1_768_embeddings: 解决问题:生成StableDiffusion 2.1图像嵌入
anony12sub34/embeddings-lehmer-6-50-roberta_squad2.0: 解决问题:处理SQuAD 2.0问答任务相关问题
mikumikugeek/embeddings02: 解决问题:暂未找到该模型具体: 解决问题信息
anony12sub34/embeddings-hamming-6-100-roberta_squad2.0: 解决问题:适用于SQuAD 2.0问答任务
[anony12sub34/embeddings-hamming-6-50-roberta_squad2.0]: 解决问题:[SQuAD 2.0问答任务嵌入问题]
[ycool/embeddings-kenny-6-50-roberta_squad2.0]: 解决问题:[处理SQuAD 2.0问答任务相关问题]
ycool/embeddings-kenny-6-100-roberta_squad2.0: 解决问题:用于SQuAD 2.0问答任务文本嵌入
tsukimiya/embeddings: 解决问题:未在huggingface找到相关: 解决问题信息
dranzerstar/SD-textual-inversion-embeddings-repo: 解决问题:用于Stable Diffusion文本反转嵌入
EvaKlimentova/knots_M2_embeddings_alphafold: 解决问题:蛋白质结构中打结相关问题分析
ProGamerGov/knollingcase-embeddings-sd-v1-5: 解决问题:用于稳定扩散v1.5的嵌入相关问题
jjetho/embeddings: 解决问题:未在huggingface找到相关信息,无法确定。
garyw/clinical-embeddings-100d-w2v-cr: 解决问题:临床文本数据的嵌入表示问题
lckidwell/embeddings: 解决问题:未在公开信息中明确其: 解决问题
rschwabco/clip-vit-base-patch32-embeddings: 解决问题:图像和文本的特征嵌入提取
garyw/clinical-embeddings-300d-w2v-cr: 解决问题:生成临床文本的词向量表示
garyw/clinical-embeddings-600d-w2v-cr: 解决问题:处理临床文本向量化问题
garyw/clinical-embeddings-100d-ft-cr: 解决问题:提供临床文本的向量嵌入表示
[garyw/clinical-embeddings-300d-ft-cr]: 解决问题:提供临床文本的词嵌入表示
garyw/clinical-embeddings-600d-ft-cr: 解决问题:提供临床领域文本嵌入表示
garyw/clinical-embeddings-100d-w2v-oa-all: 解决问题:临床文本信息的向量表示问题
garyw/clinical-embeddings-300d-w2v-oa-all: 解决问题:处理临床文本信息的嵌入表示
[garyw/clinical-embeddings-100d-ft-oa-all]: 解决问题:[生成临床文本的词向量表示]
garyw/clinical-embeddings-300d-ft-oa-all: 解决问题:生成临床文本的词向量表示
garyw/clinical-embeddings-100d-gl-cr: 解决问题:生成临床文本的词向量表示
garyw/clinical-embeddings-100d-gl-oa-all: 解决问题:生成临床文本的向量嵌入表示
[Banano/banano-sd-embeddings]: 解决问题:文本到图像生成的嵌入问题
johnsmith007/Embeddings: 解决问题:未找到该模型: 解决问题相关信息
garyw/clinical-embeddings-300d-gl-oa-all: 解决问题:生成临床文本的嵌入表示
garyw/clinical-embeddings-600d-gl-oa-all: 解决问题:临床文本信息的向量化表示
[garyw/clinical-embeddings-300d-gl-cr]: 解决问题:提供临床文本的嵌入表示
garyw/clinical-embeddings-600d-gl-cr: 解决问题:临床相关文本特征表示问题
rschwabco/facenet-embeddings: 解决问题:人脸特征提取与嵌入表示
deprem-ml/distilroberta-tweet-clustering-embeddings: 解决问题:对推文进行聚类嵌入处理
[rschwabco/clip-embeddings]: 解决问题:[图像与文本特征嵌入表示]
nekofura/Embeddings: 解决问题:未找到该模型: 解决问题的相关信息。
[LithiumBC/embeddings]: 解决问题:文本向量化及特征表示问题
pix2pix-zero-library/direction_embeddings: 解决问题:图像转换方向的嵌入表示问题
[FoodDesert/Boring_Embeddings]: 解决问题:未找到该模型: 解决问题的相关信息
nolanaatama/embeddings: 解决问题:未找到该模型: 解决问题相关信息
Kizi-Art/embeddings: 解决问题:未找到相关信息,无法明确: 解决问题。
toto10/embeddings: 解决问题:未在公开信息中找到明确: 解决问题
[EarthnDusk/Isometric_Embeddings]: 解决问题:未找到该模型: 解决问题相关信息
furgo/hb_embeddings: 解决问题:暂未在公开信息明确其: 解决问题
AmornthepKladmee/embeddings: 解决问题:未找到该模型: 解决问题的相关信息。
ilahazs/embeddings: 解决问题:未找到该模型: 解决问题相关信息
Surteng/embeddings: 解决问题:未检索到该模型相关: 解决问题信息
Loug/embeddings: 解决问题:暂未找到该模型具体: 解决问题信息
9o99/embeddings: 解决问题:暂未获取到该模型: 解决问题信息
vivi2023/embeddings: 解决问题:未找到该模型在huggingface的相关信息,无法明确: 解决问题。
hc95qc/embeddings: 解决问题:未查询到该模型相关: 解决问题信息
Seltion/embeddings: 解决问题:未找到该模型在huggingface相关信息,无法确定: 解决问题。
[Upword/gpt-neox-20b-embeddings]: 解决问题:文本向量化及特征提取
SlavyanDesu/embeddings: 解决问题:未找到该模型具体: 解决问题相关信息
shalomma/llama-7b-embeddings: 解决问题:将文本转换为向量表示
wtmsb/embeddings: 解决问题:未找到该模型相关有效信息,无法确定。
[next-social/sd-embeddings]: 解决问题:文本到图像生成相关嵌入问题
johncerpa/clip-embeddings: 解决问题:图像与文本特征嵌入问题
[dkrugman/clip-embeddings]: 解决问题:图像和文本的嵌入表示问题
rimOPS/embeddings: 解决问题:暂未获取到该模型: 解决问题信息
trinitishop14045/clip-embeddings: 解决问题:图像与文本特征嵌入问题
[deerslab/llama-7b-embeddings]: 解决问题:将文本转换为向量表示
dhanyaXchandra/embeddings: 解决问题:未找到该模型: 解决问题的相关信息
[SenY/embeddings]: 解决问题:文本向量化以用于语义分析等
ahupeter/embeddings: 解决问题:未找到该模型: 解决问题的相关信息
srodan/pleroma-inversion-embeddings: 解决问题:暂未明确该模型具体: 解决问题
JoeHart/embeddings: 解决问题:暂未找到该模型: 解决问题的相关信息
TaiouIV/embeddings: 解决问题:暂未搜索到该模型: 解决问题的相关信息。
[luxluna/embeddings]: 解决问题:未找到该模型相关信息,无法明确: 解决问题。
RealestMeri/Embeddings: 解决问题:暂未找到该模型: 解决问题的相关信息。
[gmp-dev/gmp-embeddings]: 解决问题:生成文本嵌入向量用于下游任务
KanonDes/embeddings: 解决问题:未找到相关信息,无法明确: 解决问题。
ffxvs/embeddings-collection: 解决问题:未找到明确具体: 解决问题信息
lokCX/embeddings: 解决问题:未找到该模型: 解决问题的相关信息
meeagain212/embeddings: 解决问题:未找到该模型在huggingface上的有效信息,无法明确: 解决问题。
jomcs/embeddings: 解决问题:暂未找到该模型具体: 解决问题信息
Srio/embeddings: 解决问题:未在huggingface找到相关信息,无法确定。
[SquareHat/clip-embeddings]: 解决问题:图像和文本特征嵌入问题
RectalWorm/embeddings: 解决问题:暂未找到该模型相关有效: 解决问题信息
Lucky555/embeddings: 解决问题:未找到该模型相关用途信息
michaeleliot/clip-embeddings: 解决问题:图像和文本的特征嵌入问题
2phi/embeddings: 解决问题:将文本转换为向量表示
jpohhhh/embeddings_from_msmarco-MiniLM-L-6-v3: 解决问题:信息检索与文本相似度计算
radames/blip_image_embeddings: 解决问题:将图像转换为向量嵌入表示
gunduverse/embeddings: 解决问题:未找到该模型在huggingface上相关: 解决问题信息。
TNitro/embeddings: 解决问题:暂未从公开信息获取到: 解决问题描述
ahsaputro/nolanaatama_embeddings: 解决问题:暂未找到该模型: 解决问题的相关信息。
pinapelz/embeddings: 解决问题:未找到该模型相关有效: 解决问题信息
HUNTERDEBASTADOR/embeddings: 解决问题:未在huggingface找到该模型相关有效信息,无法确定: 解决问题。
Yanderu/Embeddings: 解决问题:未在huggingface找到相关: 解决问题信息
yanuararif/embeddings: 解决问题:未在搜索中明确该模型: 解决问题
[HuynhTrong/embeddings_all_datasets_v4]: 解决问题:未在huggingface找到相关信息,无法明确。
[mlhub/embeddings]: 解决问题:未找到该模型相关有效信息,无法明确。
haodi50/embeddings: 解决问题:未找到相关信息,无法明确: 解决问题
licyk/sd-embeddings: 解决问题:用于Stable Diffusion的文本嵌入问题
AndreiBlahovici/sentence_embeddings: 解决问题:将句子转换为向量表示
Echiki/embeddings: 解决问题:未在huggingface找到该模型,无法明确: 解决问题。
stablediffusionapi/load_lora_embeddings: 解决问题:加载LoRA嵌入以增强SD模型效果
radames/segment-anything-embeddings-base: 解决问题:图像分割特征嵌入表示问题
radames/segment-anything-embeddings-large: 解决问题:图像分割特征嵌入提取
radames/segment-anything-embeddings-huge: 解决问题:图像分割特征嵌入问题
[skims/embeddings]: 解决问题:未找到该模型在huggingface上的相关信息,无法明确: 解决问题。
kazp/embeddings: 解决问题:暂未找到该模型在huggingface的有效信息,无法确定: 解决问题。
[chatbert/bert-base-cased-embeddings]: 解决问题:将文本转换为有意义向量表示
[chatbert/xlm-roberta-base-embeddings]: 解决问题:文本嵌入表示及语义理解问题
Ichiro0001/embeddings: 解决问题:暂未获取到该模型: 解决问题的相关信息。
joshuaKnauber/clip-embeddings: 解决问题:实现图像和文本的特征嵌入
ghostsniper7/embeddings: 解决问题:暂未找到该模型具体: 解决问题信息
Blaxzter/LaBSE-sentence-embeddings: 解决问题:多语言句子嵌入表示问题
seikohajimari/embeddings: 解决问题:未在huggingface查到相关: 解决问题信息
aimutation05/embeddings: 解决问题:未找到该模型在huggingface上的有效信息,无法确定: 解决问题。
botp/embeddings: 解决问题:暂未搜索到该模型具体: 解决问题信息
servbot/embeddings: 解决问题:未查询到该模型: 解决问题的相关信息。
uivid64/embeddings_sd: 解决问题:可能用于稳定扩散相关特征嵌入
[MaiKahoru/embeddingSlime]: 解决问题:未找到该模型: 解决问题的相关信息
[rahul1003/ELMo_Embeddings]: 解决问题:生成上下文相关词向量表示
axhello/embeddings: 解决问题:未查询到该模型相关: 解决问题信息
Renqf/embeddings: 解决问题:暂未找到该模型相关问题解决信息
OliAiart/embeddings: 解决问题:未搜索到该模型: 解决问题的明确信息
JCTN/embeddings: 解决问题:未找到有效信息,无法明确问题
zetavg/zh-tw-pythia-1b-a12k-f84566-embeddings-gcp-a100-trans-t3-d2ad: 解决问题:中文台湾地区文本嵌入问题
DividingSky/clip-embeddings: 解决问题:实现图像与文本的特征嵌入转换
zh-tw-llm-dv/zh-tw-pythia-6.9b-a12k-te01-embeddings-ea1: 解决问题:中文(台湾)文本向量化表示
cryptlord/embeddings: 解决问题:未找到该模型: 解决问题的相关信息
StanderPM/clips-embeddings: 解决问题:文本和图像的特征嵌入表示
brunovianna/laion-logo-embeddings: 解决问题:生成logo的嵌入表示
[brunovianna/AVA_image_clip_embeddings]: 解决问题:生成图像的CLIP嵌入表示
js101/clip-embeddings: 解决问题:图像与文本嵌入表示问题
[cundiff/clip-embeddings]: 解决问题:实现图像和文本的特征嵌入转换
zh-tw-llm-dv/zh-tw-llm-ta01-pythia-1b-ta8000-v1-a_1_embeddings-a100-t02-3d435e: 解决问题:未找到该模型: 解决问题的明确信息。
[uretan/clip-embeddings]: 解决问题:图像和文本的特征嵌入表示
zh-tw-llm-dv/zh-tw-llm-ta01-pythia-1b-ta8000-v1-b_1_embeddings_and_attention-a100-t02-713b8e: 解决问题:暂未找到该模型: 解决问题的相关信息
zh-tw-llm-dv/zh-tw-llm-ta01-pythia-6.9b-ta8000-v1-a_1_embeddings-h100-t01-c5daa1: 解决问题:暂未找到该模型: 解决问题的相关信息。
igorsantana/rnn-embeddings-songs: 解决问题:生成歌曲的RNN嵌入表示
zh-tw-llm-dv/zh-tw-llm-ta01-pythia-6.9b-ta8000-v1-a_1_embeddings-h100-t01-c5daa1-8bit: 解决问题:未找到相关信息,无法明确: 解决问题
zetavg/zh-tw-llm-ta01-pythia-6.9b-ta8000-v1-a_1_embeddings-h100-t01-c5daa1-8bit-2: 解决问题:暂未获取到该模型具体: 解决问题信息
Word2vec/polyglot_words_embeddings_afr: 解决问题:将南非荷兰语单词转换为向量

关于图相关的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
florentgbelidji/blip_image_embeddings: 解决问题:将图像转换为向量嵌入表示 
crumb/ViT-L-14-Token-Embeddings: 解决问题:图像视觉特征的嵌入表示问题
ProGamerGov/knollingcase-embeddings-sd-v2-0: 解决问题:生成特定风格图像嵌入表示
KnutJaegersberg/sentence_transformer_mpnet_v2_to_kg_embeddings_wikidata5m: 解决问题:将句子转换为知识图谱嵌入
ProGamerGov/winter-cat-embeddings-sd-v2-1: 解决问题:用于StableDiffusion生成特定风格图像
Priyanshu9991/sd2.1_768_embeddings: 解决问题:生成StableDiffusion 2.1图像嵌入
rschwabco/clip-vit-base-patch32-embeddings: 解决问题:图像和文本的特征嵌入提取
[Banano/banano-sd-embeddings]: 解决问题:文本到图像生成的嵌入问题
[rschwabco/clip-embeddings]: 解决问题:[图像与文本特征嵌入表示]
pix2pix-zero-library/direction_embeddings: 解决问题:图像转换方向的嵌入表示问题
[next-social/sd-embeddings]: 解决问题:文本到图像生成相关嵌入问题
johncerpa/clip-embeddings: 解决问题:图像与文本特征嵌入问题
[dkrugman/clip-embeddings]: 解决问题:图像和文本的嵌入表示问题
trinitishop14045/clip-embeddings: 解决问题:图像与文本特征嵌入问题
[SquareHat/clip-embeddings]: 解决问题:图像和文本特征嵌入问题
michaeleliot/clip-embeddings: 解决问题:图像和文本的特征嵌入问题
radames/blip_image_embeddings: 解决问题:将图像转换为向量嵌入表示
radames/segment-anything-embeddings-base: 解决问题:图像分割特征嵌入表示问题
radames/segment-anything-embeddings-large: 解决问题:图像分割特征嵌入提取
radames/segment-anything-embeddings-huge: 解决问题:图像分割特征嵌入问题
joshuaKnauber/clip-embeddings: 解决问题:实现图像和文本的特征嵌入
DividingSky/clip-embeddings: 解决问题:实现图像与文本的特征嵌入转换
StanderPM/clips-embeddings: 解决问题:文本和图像的特征嵌入表示
[brunovianna/AVA_image_clip_embeddings]: 解决问题:生成图像的CLIP嵌入表示
js101/clip-embeddings: 解决问题:图像与文本嵌入表示问题
[cundiff/clip-embeddings]: 解决问题:实现图像和文本的特征嵌入转换
[uretan/clip-embeddings]: 解决问题:图像和文本的特征嵌入表示

LangChain构建 Chroma

Posted on 2025-06-25

先要安装依赖

1
pip install langchain-chroma

Chroma可以以多种模式运行。以下是每种模式的示例,均与LangChain集成:

  • in-memory-在Python脚本或Jupyter笔记本中
  • in-memory with persistance-在脚本或笔记本中保存/加载到磁盘
  • in a docker container-作为在本地机器或云中运行的服务器

与任何其他数据库一样,您可以进行以下操作:

  • add
  • get
  • update
  • upsert
  • delete
  • peek

而.query则运行相以性搜索。查看完整文档,请访问docs。要直接访问这些方法,可以使用,_collection.method()。

基本示例在这个基本示例中,我们获取《乔布斯演讲稿》,将其分割成片段,使用开源嵌入模型进行嵌入,加载到Chroma中,然后进行查询。

乔布斯演讲知识库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# knowledge.txt

Thank you. I'm honored to be with you today for your commencement from one of the finest universities in the world. Truth be told, I never graduated from college and this is the closest I've ever gotten to a college graduation.
谢谢大家。很荣幸能和你们,来自世界最好大学之一的毕业生们,一块儿参加毕业典礼。老实说,我大学没有毕业,今天恐怕是我一生中离大学毕业最近的一次了。

Today I want to tell you three stories from my life. That's it. No big deal. Just three stories.
今天我想告诉大家来自我生活的三个故事。没什么大不了的,只是三个故事而已。

The first story is about connecting the dots.
第一个故事,如何串连生命中的点滴。

I dropped out of Reed College after the first six months but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out? It started before I was born. My biological mother was a young, unwed graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife, except that when I popped out, they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking, "We've got an unexpected baby boy. Do you want him?" They said, "Of course." My biological mother found out later that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would go to college.
我在里得大学读了六个月就退学了,但是在18个月之后--我真正退学之前,我还常去学校。为何我要选择退学呢?这还得从我出生之前说起。我的生母是一个年轻、未婚的大学毕业生,她决定让别人收养我。她有一个很强烈的信仰,认为我应该被一个大学毕业生家庭收养。于是,一对律师夫妇说好了要领养我,然而最后一秒钟,他们改变了主意,决定要个女孩儿。然后我排在收养人名单中的养父母在一个深夜接到电话,“很意外,我们多了一个男婴,你们要吗?”“当然要!”但是我的生母后来又发现我的养母没有大学毕业,养父连高中都没有毕业。她拒绝在领养书上签字。几个月后,我的养父母保证会让我上大学,她妥协了。

This was the start in my life. And 17 years later, I did go to college, but I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life, and no idea of how college was going to help me figure it out, and here I was, spending all the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back, it was one of the best decisions I ever made. The minute I dropped out, I could stop taking the required classes that didn't interest me and begin dropping in on the ones that looked far more interesting.
这是我生命的开端。十七年后,我上大学了,但是我很无知地选了一所差不多和斯坦福一样贵的学校,几乎花掉我那蓝领阶层养父母一生的积蓄。六个月后,我觉得不值得。我看不出自己以后要做什么,也不晓得大学会怎样帮我指点迷津,而我却在花销父母一生的积蓄。所以我决定退学,并且相信没有做错。一开始非常吓人,但回忆起来,这却是我一生中作的最好的决定之一。从我退学的那一刻起,我可以停止一切不感兴趣的必修课,开始旁听那些有意思得多的课。

It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms. I returned Coke bottles for the five-cent deposits to buy food with, and I would walk the seven miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example.
事情并不那么美好。我没有宿舍可住,睡在朋友房间的地上。为了吃饭,我收集五分一个的旧可乐瓶,每个星期天晚上步行七英里到哈尔-克里什纳庙里改善一下一周的伙食。我喜欢这种生活方式。能够遵循自己的好奇和直觉前行后来被证明是多么的珍贵。让我来给你们举个例子吧。

Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer was beautifully hand-calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and sans-serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating.
当时的里德大学提供可能是全国最好的书法指导。校园中每一张海报,抽屉上的每一张标签,都是漂亮的手写体。由于我已退学,不用修那些必修课,我决定选一门书法课上上。在这门课上,我学会了“serif”和"sans-serif"两种字体、学会了怎样在不同的字母组合中改变字间距、学会了怎样写出好的字来。这是一种科学无法捕捉的微妙,楚楚动人、充满历史底蕴和艺术性,我觉得自己被完全吸引了。

None of this had even a hope of any practical application in my life. But ten years later when we were designing the first Macintosh computer, it all came back to me, and we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts, and since Windows just copied the Mac, it's likely that no personal computer would have them.
当时我并不指望书法在以后的生活中能有什么实用价值。但是,十年之后,我们在设计第一台 Macintosh计算机时,它一下子浮现在我眼前。于是,我们把这些东西全都设计进了计算机中。这是第一台有这么漂亮的文字版式的计算机。要不是我当初在大学里偶然选了这么一门课,Macintosh计算机绝不会有那么多种印刷字体或间距安排合理的字号。要不是Windows照搬了 Macintosh,个人电脑可能不会有这些字体和字号。

If I had never dropped out, I would have never dropped in on that calligraphy class and personals computers might not have the wonderful typography that they do.
要不是退了学,我决不会碰巧选了这门书法课,个人电脑也可能不会有现在这些漂亮的版式了。

Of course it was impossible to connect the dots looking forward when I was in college, but it was very, very clear looking backwards ten years later. Again, you can't connect the dots looking forward. You can only connect them looking backwards, so you have to trust that the dots will somehow connect in your future. You have to trust in something--your gut, destiny, life, karma, whatever--because believing that the dots will connect down the road will give you the confidence to follow your heart, even when it leads you off the well-worn path, and that will make all the difference.
当然,我在大学里不可能从这一点上看到它与将来的关系。十年之后再回头看,两者之间关系就非常、非常清楚了。你们同样不可能从现在这个点上看到将来;只有回头看时,才会发现它们之间的关系。所以你必须相信,那些点点滴滴,会在你未来的生命里,以某种方式串联起来。你必须相信一些东西——你的勇气、宿命、生活、因缘,随便什么——因为相信这些点滴能够一路连接会给你带来循从本觉的自信,它使你远离平凡,变得与众不同。

My second story is about love and loss. I was lucky. I found what I loved to do early in life. Woz and I started Apple in my parents' garage when I was 20. We worked hard and in ten years, Apple had grown from just the two of us in a garage into a $2 billion company with over 4,000 employees. We'd just released our finest creation, the Macintosh, a year earlier, and I'd just turned 30, and then I got fired. How can you get fired from a company you started? Well, as Apple grew, we hired someone who I thought was very talented to run the company with me, and for the first year or so, things went well. But then our visions of the future began to diverge, and eventually we had a falling out. When we did, our board of directors sided with him, and so at 30, I was out, and very publicly out. What had been the focus of my entire adult life was gone, and it was devastating. I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down, that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure and I even thought about running away from the Valley. But something slowly began to dawn on me. I still loved what I did. The turn of events at Apple had not changed that one bit. I'd been rejected but I was still in love. And so I decided to start over.
第二个故事是关于爱与失的。我很幸运,很早就发现自己喜欢做的事情。我二十岁的时候就和沃茨在父母的车库里开创了苹果公司。我们工作得很努力,十年后,苹果公司成长为拥有四千名员工,价值二十亿的大公司。我们刚刚推出了最好的创意,Macintosh操作系统,在这之前的一年,也就是我刚过三十岁,我被解雇了。你怎么可能被一个亲手创立的公司解雇?事情是这样的,在公司成长期间,我雇佣了一个我们认为非常聪明,可以和我一起经营公司的人。一年后,我们对公司未来的看法产生分歧,董事会站在了他的一边。于是,在我三十岁的时候,我出局了,很公开地出局了。我整个成年生活的焦点没了,这很要命。一开始的几个月我真的不知道该干什么。我觉得我让公司的前一代创建者们失望了,我把传给我的权杖给弄丢了。我与戴维德·帕珂德和鲍勃·诺埃斯见面,试图为这彻头彻尾的失败道歉。我败得如此之惨以至于我想要逃离硅谷。但有个东西在慢慢地叫醒我:我还爱着我从事的行业。这次失败一点儿都没有改变这一点。我被逐了,但我仍爱着我的事业。我决定重新开始。

I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods in my life. During the next five years I started a company named NeXT, another company named Pixar and fell in love with an amazing woman who would become my wife. Pixar went on to create the world's first computer-animated feature film, "Toy Story," and is now the most successful animation studio in the world.
当时我没有看出来,但事实证明“被苹果开除”是发生在我身上最好的事。成功的重担被重新起步的轻松替代,对任何事情都不再特别看重,这让我感觉如此自由,进入一生中最有创造力的阶段。接下来的五年,我创立了一个叫NeXT的公司,接着又建立了Pixar,然后与后来成为我妻子的女人相爱。Pixar出品了世界第一个电脑动画电影:“玩具总动员”,现在它已经是世界最成功的动画制作工作室了。

In a remarkable turn of events, Apple bought NeXT and I returned to Apple and the technology we developed at NeXT is at the heart of Apple's current renaissance, and Lorene and I have a wonderful family together.
在一系列的成功运转后,苹果收购了NeXT,我又回到了苹果。我们在NeXT开发的技术在苹果的复兴中起了核心作用,另外劳琳和我组建了一个幸福的家庭。

I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful-tasting medicine but I guess the patient needed it. Sometimes life's going to hit you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love, and that is as true for work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work, and the only way to do great work is to love what you do. If you haven't found it yet, keep looking, and don't settle. As with all matters of the heart, you'll know when you find it, and like any great relationship it just gets better and better as the years roll on. So keep looking. Don't settle.
我非常确信,如果我没有被苹果炒掉,这些就都不会发生。这个药的味道太糟了,但是我想病人需要它。有些时候,生活会给你迎头一棒。不要丧失信心。我确信唯一让我一路走下来的是我对自己所做事情的热爱。你必须去找你热爱的东西,对工作如此,对你的爱人也是这样的。工作会占据你生命中很大的一部分,你只有相信自己做的是伟大的工作,你才能怡然自得。如果你还没有找到,那么就继续找,不要停。全心全意地找,当你找到时,你会知道的。就像任何真诚的关系,随着时间的流逝,只会越来越紧密。所以继续找,不要停。

My third story is about death. When I was 17 I read a quote that went something like "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself, "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "no" for too many days in a row, I know I need to change something. Remembering that I'll be dead soon is the most important thing I've ever encountered to help me make the big choices in life, because almost everything--all external expectations, all pride, all fear of embarrassment or failure--these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.
我的第三个故事关于死亡。我17岁的时候读到过一句话“如果你把每一天都当作最后一天过,有一天你会发现你是正确的”。这句话给我留下了深刻的印象。从那以后,过去的33年,每天早上我都会对着镜子问自己:“如果今天是我的最后一天,我会不会做我想做的事情呢?”如果连着一段时间,答案都是否定的的话,我就知道我需要改变一些东西了。提醒自己就要死了是我遇见的最大的帮助,帮我作了生命中的大决定。因为几乎任何事——所有的荣耀、骄傲、对难堪和失败的恐惧——在死亡面前都会消隐,留下真正重要的东西。提醒自己就要死亡是我知道的最好的方法,用来避开担心失去某些东西的陷阱。你已经赤裸裸了,没有理由不听从于自己的心愿。

About a year ago, I was diagnosed with cancer. I had a scan at 7:30 in the morning and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctors' code for "prepare to die." It means to try and tell your kids everything you thought you'd have the next ten years to tell them, in just a few months. It means to make sure that everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.
大约一年前,我被诊断出患了癌症。我早上七点半作了扫描,清楚地显示在我的胰腺有一个肿瘤。我当时都不知道胰腺是什么东西。医生们告诉我这几乎是无法治愈的,我还有三到六个月的时间。我的医生建议我回家,整理一切。在医生的辞典中,这就是“准备死亡”的意思。就是意味着把要对你小孩说十年的话在几个月内说完;意味着把所有东西搞定,尽量让你的家庭活得轻松一点;意味着你要说“永别”了。

I lived with that diagnosis all day. Later that evening I had a biopsy where they stuck an endoscope down my throat, through my stomach into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated but my wife, who was there, told me that when they viewed the cells under a microscope, the doctor started crying, because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and, thankfully, I am fine now.
我整日都想着那诊断书的事情。后来有天晚上我做了一个活切片检查,他们将一个内窥镜伸进我的喉咙,穿过胃,到达肠道,用一根针在我的胰腺肿瘤上取了几个细胞。我当时是被麻醉的,但是我的妻子告诉我,那些医生在显微镜下看到细胞的时候开始尖叫,因为发现这竟然是一种非常罕见的可用手术治愈的胰腺癌症。我做了手术,现在,我痊愈了。

This was the closest I've been to facing death, and I hope it's the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept. No one wants to die, even people who want to go to Heaven don't want to die to get there, and yet, death is the destination we all share. No one has ever escaped it. And that is as it should be, because death is very likely the single best invention of life. It's life's change agent; it clears out the old to make way for the new. right now, the new is you. But someday, not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it's quite true. Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma, which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice, and most important, have the courage to follow heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.
这是我最接近死亡的时候,我也希望是我未来几十年里最接近死亡的一次。这次死里逃生让我比以往只知道死亡是一个有用而纯粹书面概念的时候更确信地告诉你们,没有人愿意死,即使那些想上天堂的人们也不愿意通过死亡来达到他们的目的。但是死亡是每个人共同的终点,没有人能够逃脱。也应该如此,因为死亡很可能是生命最好的发明。它去陈让新。现在,你们就是“新”。但是有一天,不用太久,你们有会慢慢变老然后死去。抱歉,这很戏剧性,但却是真的。你们的时间是有限的,不要浪费在重复别人的生活上。不要被教条束缚,那意味着会和别人思考的结果一块儿生活。不要被其他人的喧嚣观点掩盖自己内心真正的声音。你的直觉和内心知道你想要变成什么样子。所有其他东西都是次要的。

When I was young, there was an amazing publication called _The Whole Earth Catalogue_, which was one of the bibles of my generation. It was created by a fellow named Stuart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960s, before personal computers and desktop publishing, so it was all made with typewriters, scissors, and Polaroid cameras. it was sort of like Google in paperback form 35 years before Google came along. It was idealistic, overflowing with neat tools and great notions. Stuart and his team put out several issues of the _The Whole Earth Catalogue_, and then when it had run its course, they put out a final issue. It was the mid-1970s and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitch-hiking on if you were so adventurous. Beneath were the words, "Stay hungry, stay foolish." It was their farewell message as they signed off. "Stay hungry, stay foolish." And I have always wished that for myself, and now, as you graduate to begin anew, I wish that for you. Stay hungry, stay foolish.
我年轻的时候,有一份叫做《完整地球目录》的好杂志,是我们这一代人的圣经之一。它是一个叫斯纠华特·布兰的、住在离这不远的曼罗公园的家伙创立的。他用诗一般的触觉将这份杂志带到世界。那是六十年代后期,个人电脑出现之前,所以这份杂志全是用打字机、剪刀和偏光镜制作的。有点像软皮包装的google,不过却早了三十五年。它理想主义,全文充斥着灵巧的工具和伟大的想法。斯纠华特和他的小组出版了几期“完整地球目录”,在完成使命之前,他们出版了最后一期。那是七十年代中期,我和你们差不多大。最后一期的封底是一张清晨乡村小路的照片,如果你有冒险精神,可以自己找到这条路。下面有一句话,“保持饥饿,保持愚蠢”。这是他们的告别语,“保持饥饿,保持愚蠢”。我常以此勉励自己。现在,在你们即将踏上新旅程的时候,我也希望你们能这样。保持饥饿,保持愚蠢。

Thank you all, very much.
非常感谢。

下面是一个完整的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#示例:chroma_base.py
# pip install langchain
# pip install langchain-community
# pip install langchain-chroma
from langchain_chroma import Chroma
from langchain_community.document_loaders import TextLoader
# pip install -U langchain-huggingface
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_text_splitters import CharacterTextSplitter
#加载文指并将其分割成片段
loader = TextLoader("../knowledge.txt",encoding="UTF-8")
documents = loader.load()
#将其分割成片段
text_splitter = CharacterTextSplitter(chunk_size=1500,chunk_overlap=0)
docs = text_splitter.split_documents(documents)
#创建开源嵌入函数
embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
#将其加载到Chroma中
db = Chroma.from_documents(docs,embedding_function)
#进行查询
query = "Pixar公司是做什么的?"
docs = db.similarity_search(query)
#打印结果
print(docs[0].page_content)

持久化

如果我们希望将向量持久化到磁盘可以按照下面方式写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# pip install langchain-chroma
import chromadb
from langchain_chroma import Chroma
# pip install -U langchain-huggingface
from langchain_huggingface import HuggingFaceEmbeddings


persistent_client = chromadb.PersistentClient()
#创建开源族入丽数
embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
collection = persistent_client.get_or_create_collection("collection_name")
collection.add(ids=["1","2","3"],documents=["a","b","c"])
langchain_chroma = Chroma(
client=persistent_client,
collection_name="collection_name",
embedding_function=embedding_function,
)
print("在年合中有", langchain_chroma._collection.count(),"个文档")

CRUD

下面是一个简单的增删改查可以体会一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

import chromadb
# pip install langchain-chroma
from langchain_chroma import Chroma
# pip install langchain-text-splitters
from langchain_text_splitters import CharacterTextSplitter

from langchain_community.document_loaders import TextLoader
from langchain_huggingface import HuggingFaceEmbeddings

loader = TextLoader("/content/onedrive/colab/knowledge.txt",encoding="UTF-8")
documents = loader.load()
# #将其分割成片段
text_splitter = CharacterTextSplitter(chunk_size=1500,chunk_overlap=0)
docs = text_splitter.split_documents(documents)
# #创建开源嵌入函数
embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
query="Pixar公司是做什么的?"
# #创建简单的ids
ids = [str(i) for i in range(1,len(docs)+1)]
#添加数据
example_db = Chroma.from_documents(docs,embedding_function,ids=ids)
docs = example_db.similarity_search(query)
#更新文档的元数据
docs[0].metadata = {
"source":"/content/onedrive/colab/knowledge.txt",
"new_value":"hello world",
}

print("更所前内容:")
print(example_db._collection.get(ids=[ids[0]]))
example_db.update_document(ids[0],docs [0])
print("更新后内容:")
print(example_db._collection.get(ids=[ids[0]]))

print("删除前计数",example_db._collection.count())
print(example_db._collection.get(ids=[ids[-1]]))
example_db._collection.delete(ids=[ids[-1]])
print("删除后计数",example_db._collection.count())
print(example_db._collection.get(ids=[ids[-1]]))

使用openAI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#示例:chroma._openai.py
from langchain_openai import OpenAIEmbeddings
# pip install langchain-chroma
from langchain_chroma import Chroma
import chromadb
from langchain_text_splitters import CharacterTextsplitter
from langchain_community.document_loaders import TextLoader
embeddings = OpenAIEmbeddings()
persistent_client = chromadb.Persistentclient()
new_client = chromadb.Ephemeralclient()
#加载文档并将其分剖成片段
loader = TextLoader("../../resource/knowledge.txt",encoding="UTF-8")
documents = loader.load()
#将其分割成片段
text_splitter = CharacterTextsplitter(chunk_size=1500,chunk_overlap=0)
docs = text_splitter.split_documents(documents)
openai_lc_client = Chroma.from_documents(
docs,embeddings,client=new_client,collection_name="openai_collection"
)
query="Pixar公司是做什么的?"
docs = openai_lc_client.similarity_search(query)
print(docs[0].page_content)

Embedding与向量数据库

Posted on 2025-06-25

向量数据库

向量数据库(Vector Database),也叫矢量数据库,主要用来存储和处理向量数据。在数学中,向量是有大小和方向的量,可以使用带箭头的线段表示,箭头指向即为向量的方向,线段的长度表示向量的大小。两个向量的距离或者相似性可以通过欧式距离或者余弦距离得到。图像、文本和音视频这种非结构化数据都可以通过某种变换或者嵌入学习转化为向量数据存储到向量数据库中,从而实现对图像、文本和音视频的相似性搜索和检索。这意味着您可以使用向量数据库根据语义或上下文含义查找最相似或相关的数据,而不是使用基于精确匹配或预定义标准查询数据库的传统方法。向量数据库的主要特点是高效存储与检索。利用索引技术和向量检索算法能实现高维大数据下的快速响应。向量数据库也是一种数据库,除了要管理向量数据外,还是支持对传统结构化数据的管理。实际使用时,有很多场景会同时对向量字段和结构化字段进行过滤检索,这对向量数据库来说也是一种挑战

向量嵌入

对于传统数据库,搜索功能都是基于不同的索引方式(BTree、倒排索引等)加上精确匹配和排序算法(BM25、TF-DF)等实现的。本质还是基于文本的精确匹配,这种索引和搜索算法对于关键字的搜索功能非常合适,但对于语义搜索功能就非常弱。

例如,如果你搜索“小狗”,那么你只能得到带有“小狗”关键字相关的结果,而无法得到“柯基”“金毛”等结果,因为“小狗”和“金毛”是不同的词,传统数据库无法识别它们的语义关系,所以传统的应用需要人为的将“小狗”和“金毛”等词之间打上特征标签进行关联,这样才能实现语义搜索。而如何将生成和挑选特征这个过程,也被称为Feature Engineering(特征工程),它是将原始数据转化成更好的表达问题本质的特征的过程。

但是如果你需要处理非结构化的数据,就会发现非结构化数据的特征数量会开始快速膨胀,例如我们处理的是图像、音频、视频等数据,这个过程就变得非常困难。例如,对于图像,可以标注颜色、形状、纹理、边缘、对象、场景等特征,但是这些特征太多了,而且很难人为的进行标注,所以我们需要一种自动化的方式来提取这些特征,而这可以通过Vector Embedding实现。

Vector Embedding是由AI模型(例如大型语言模型LLM)生成的,它会根据不同的算法生成高维度的向量数据,代表着数据的不同特征,这些特征代表了数据的不同维度。例如,对于文本,这些特征可能包括词汇、语法、语义、情感、情绪、主题、上下文等。对于音频,这些特征可能包括音调、节奏、音高、音色、音量、语音、音乐等。

例如对于目前来说,文本向量可以通过OpenAl的text-embedding-ada-O02模型生成,图像向量可以通过clip-vit-base-patch32模型生成,而音频向量可以通过wav2vec2-base-960h模型生成。这些向量都是通过AI模型生成的,所以它们都是具有语义信息的。

例如我们将这句话“Your text string goes here”用text-embedding-ada-002模型进行文本Embedding,它会生成一个1536维的向量,得到的结果是这样:“-0.006929283495992422,-0.005336422007530928,·,-454713225452536e-05,-0,024047505110502243”,它是一个长度为1536的数组。这个向量就包含了这句话的所有特征,这些特征包括词汇、语法,我们可以将它存入向量数据库中,以便我们后续进行语义搜索。

特征和向量

虽然向量数据库的核心在于相似性搜索(Similarity Search),但在深入了解相似性搜索前,我们需要先详细了解一下特征和向量的概念和原理。

我们先思考一个问题?为什么我们在生活中区分不同的物品和事物?

如果从理论角度出发,这是因为我门会通过源别不同事物之间不同的特征来识别种类,例如分别不同种类的小狗,就可以适过体型大小.毛发长层、旱子长短等烤证来区分。如下面这张照片按照体型序,可以看到体型拉入的狗靠近坐标抽右边,这样就能得到-一个体型特征的一维坐和对应的数值,从0到1的数字中得到每只狗在坐标系中的位置。

image.png

然而单靠一个体型大小的特征并不够,像照片中哈士奇、金毛和拉布拉多的体型就非常接近,我们无法区分。所以我们会继续观察其它的特征,例如毛发的长短。

image.png

这样每只狗对应一个二维坐标点,我们就能轻易的将哈士奇、金毛和拉布拉多区分开来,如果这时仍然无法很好的区分德牧和罗威纳犬。我们就可以继续再从其它的特征区分,比如鼻子的长短,这样就能得到个三维的坐标系和每只狗在三维坐标系中的位置。
在这种情况下,只要特征足够多,就能够将所有的狗区分开来,最后就能得到一个高维的坐标系,虽然我们想象不出高维坐标系长什么样,但是在数组中,我们只需要一直向数组中追加数字就可以了。
实际上,只要维度够多,我们就能够将所有的事物区分开来,世间万物都可以用一个多维坐标系来表示,它们都在一个高维的特征空间中对应着一个坐标点。
那这和相似性搜索(Similarity Search)有什么关系呢?你会发现在上面的二维坐标中,德牧和罗威纳犬的坐标就非常接近,这就意味着它们的特征也非常接近。我们都知道向量是具有大小和方向的数学结构,所以可以将这些特征用向量来表示,这样就能够通过计算向量之间的距离来判断它们的相似度,这就是相似性测量

相似性测量(Similarity Measurement)

上面我们讨论了向量数据库的不同搜索算法,但是还没有讨论如何衡量相似性。在相似性搜索中,需要计算两个向量之间的距离,然后根据距离来判断它们的相似度。而如何计算向量在高维空间的距离呢?有三种常见的向量相似度算法:欧几里德距离、余弦相似度和点积相似度。

欧几里得距离(Euclidean Distance)

欧几里得距离是用于衡量两个点(或向量)之间的直线距离的一种方法。它是最常用的距离度量之一,尤其在几何和向量空间中。可以将其理解为两点之间的“直线距离”。

其中,A和B分别表示两个向量,n表示向量的维度。

公式

对于两个向量A=(a1,a2,·,an)和B=(b1,b2,·,bn),它们之间的欧几里得距离可以计算为:

image.png

对应的图片为

image.png

image.png

欧几里得距离算法的优点是可以反映向量的绝对距离,适用于需要考虑向量长度的相似性计算。例如推荐系统中,需要根据用户的历史行为来推荐相似的商品,这时就需要考虑用户的历史行为的数量,而不仅仅是用户的历史行为的相似度。

余弦相似度(Cosine Similarity)

余弦相似度(Cosine Similarity)是一种用于衡量两个向量之间相似度的指标。它通过计算两个向量夹角
的余弦值来判断它们的相似程度。其值介于-1和1之间,通常用于文本分析和推荐系统等领域:

image.png

A·B是向量的点积
||A||和‖B||是向量的范数(即向量的长度)
计算步骤

  1. 点积计算:计算两个向量的点积,即各个对应元素相乘再求和。
  2. 范数计算:计算每个向量的范数,通常是欧几里得范数,即每个元素平方和的平方根。
  3. 代入公式:将点积和范数代入公式,得到余弦相似度。

image.png

特点

值域:结果在-1到1之间。1表示完全相似,0表示不相关,-1表示完全相反。
余弦相似度对向量的长度不敏感,只关注向量的方向,因此适用于高维向量的相似性计算。例如语义搜索和文档分类。

image.png

相似性搜索(Similarity Search)

既然我们知道了可以通过比较向量之间的距离来判断它们的相似度,那么如何将它应用到真实的场景中呢?如果想要在一个海量的数据中找到和某个向量最相似的向量,我们需要对数据库中的每个向量进行一次比较计算,但这样的计算量是非常巨大的,所以我们需要一种高效的算法来解决这个问题。高效的搜索算法有很多,其主要思想是通过两种方式提高搜索效率:

1)减少向量大小一通过降维或减少表示向量值的长度。
2)缩小搜索范围一可以通过聚类或将向量组织成基于树形、图形结构来实现,并限制搜索范围仅在最接近的簇中进行,或者通过最相似的分支进行过滤。

我们首先来介绍一下大部分算法共有的核心概念,也就是聚类。

K-Means

我们可以在保存向量数据后,先对向量数据先进行聚类。例如下图在二维坐标系中,划定了4个聚类中心,然后将每个向量分配到最近的聚类中心,经过聚类算法不断调整聚类中心位置,这样就可以将向量数据分成4个簇。每次搜索时,只需要先判断搜索向量属于哪个簇,然后再在这一个簇中进行搜索,这样就从4个簇的搜索范围减少到了1个簇,大大减少了搜索的范围。

image.png

工作原理
1.初始化:选择k个随机点作为初始聚类中心。
2.分配:将每个向量分配给离它最近的聚类中心,形成k个簇。
3.更新:重新计算每个簇的聚类中心,即簇内所有向量的平均值。
4.迭代:重复“分配”和“更新”步骤,直到聚类中心不再变化或达到最大迭代次数。

举例说明
假设我们有一组二维向量(点),例如:「(1,2),(2,1),(4,5),(5,4),(8,9)川,我们希望将它们聚成四个簇(
k=4)。
1.初始化:随机选择四个点作为初始聚类中心,比如(1,2)、(2,1)、(4,5)和(8,9)。
2.分配:计算每个点到四个聚类中心的距离,将每个点分配给最近的聚类中心。
形成四个簇:[(1,2)],[(2,1)],[(4,5),(5,4)],[(8,9)]

  • 点(1,2)更接近(1,3)
  • 点(2,1)更接近(2,1)
  • 点(4,5)更接近(4,5)
  • 点(5,4)更接近(4,5)
  • 点(8,9)更接近(8,9)

3.更新:计算每个簇的新聚类中心

  • 第一个簇的聚类中心是(1,2)
  • 第二个簇的聚类中心是(2,1)
  • 第三个簇的新聚类中心是(4+5)/2,(5+4)/2)=(4.5,4.5)
  • 第四个簇的聚类中心是(8,9)

4.迭代:重复分配和更新步骤,直到聚类中心不再变化。

优点:通过将向量聚类,我们可以在进行相似性搜索时只需计算查询向量与每个聚类中心之间的距离,而不是与所有向量计算距离。这大大减少了计算量,提高了搜索效率。这种方法在处大规慎数据时尤其有效,可以显著加快搜索速度。

缺点,例如在搜索的时候,如果搜索的内容正好处于两个分类区域的中间,就很有可能遗漏掉最相似的向量。

Hierarchical Navigable Small Worlds (HNSW)

除了聚类以外,也可以通过构建树或者构建图的方式来实现近似最近邻搜索。这种方法的基本思想是每次将向量加到数据库中的时候,就先找到点它最相邻的向量,然后将它们连接起来,这样就构成了一个图。当需要搜索的时候,就可以从图中的某个节点开始,不断的进行最相邻捷豪和最短路径计算,直到找到最相似的向量。这种算法能保证搜索的质量,但是如果图中所以的节点都以最短的路径相连,如图中最下面的一层,那么在搜索的时候,就同样需要遍历所有的节点。

image.png

解决这个问题的思路与常见的跳表算法相以,如下图要搜索跳表,从最高层开始,沿着具有最长“跳过的边向右移动。如果发现当前节点的值大于要搜索的值-我们知道已经超过了目标,因此我们会在下一级中向前一个节点。

image.png

通过一个简单的例子来说明HNSW的工作原理。
假设我们有以下五个二维向量:

  • A=(1,2)
  • B=(2,3)
  • C=(3,4)
  • D=(8,9
  • E=(9,10)
    我们要使用HNSW来找到与查询向量Q=(2,2)最相似的向量。

image.png

image.png

总结: 通过这种层次化的搜索过程,HNSW能够快速缩小搜索范围,在大规模数据中高效找到近以最近邻。

基于Embedding的问答助手和意图匹配

Embedding models(嵌入模型)

Embeddings类是一个专为与文本嵌入模型进行交互而设计的类。有许多嵌入模型提供商(如OpenAl.Cohere、Hugging Face等)-这个类旨在为它们提供一个标准接口。

Embeddings类会为文本创建一个向量表示。这很有用,因为这意味着我们可以在向量空间中思考文本,并做一些类似语义搜索的事情,比如在向量空间中寻找最相似的文本片段。

LangChain中的基本Embeddings类提供了两种方法:一个用于嵌入文档,另一个用于嵌入查询。前者,embed_documents接受多个文本作为输入,而后者.embed_query接受单个文本。之所以将它们作为两个单独的方法,是因为一些嵌入提供商对文档(要搜索的文档)和查询(搜索查询本身)有不同的嵌入方法。

.embed_.query将返回一个浮点数列表,而.embed._documents将返回一个浮点数列表的列表。

image.png

设置OpenAl
首先,我们需要安装OpenAl合作伙伴包:

1
pip install langchain-openai

访问AP需要一个API密钥,您可以通过创建帐户并转到这里来获取它。一旦我们有了密钥,我们希望通过运行以下命令将其设置为环境变量:

1
export OPENAI_API KEY="..."

如果您不想设置环境变量,可以在初始化OpenAl LLM类时通过api_key命名参数直接传递密钥:

1
2
from langchain_openai import OpenAIEmbeddings
embeddings_model OpenAIEmbeddings(api_key="...")

否则,您可以不带任何参数初始化:

1
2
from langchain_openai import OpenAIEmbeddings
embeddings_model OpenAIEmbeddings()

完整的Case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# pip install langchain-openai

from langchain_openai import OpenAIEmbeddings
embeddings_model = OpenAIEmbeddings()
embeddings = embeddings_model.embed_documents(
[
"嗨!",
"哦,你好!",
"你叫什么名字?",
"我的朋及们叫我World",
"Hello World!"
]
)
#第一个打印是embeddings/的文本数量,第二个打印是第一段文本的embed中ing向量维度
print(len(embeddings),len(embeddings[0]))

image.png

嵌入单个查询(embed query)

使用.embed_query来嵌入单个文本片段(例如,用于与其他嵌入的文本片段进行t比较)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# pip install langchain-openai

from langchain_openai import OpenAIEmbeddings
embeddings_model = OpenAIEmbeddings()
embeddings = embeddings_model.embed_documents(
[
"嗨!",
"哦,你好!",
"你叫什么名字?",
"我的朋及们叫我World",
"Hello World!"
]
)
embedded_query=embeddings_model.embed_query("对话中提到的名字是什么?")
#查询嵌入的前五个值
print(embedded_query[:5])

输出结果

1
2

[0.603292866277936101,-0.689463472291827282,0.03418809175491333,-0.8811715596774592996,...]

问答助手

从知识库中,找到一个和问题最接近的类似问题。我的知识库集合为:

1
2
3
4
"OpenAI的ChatGPT,是一个强大的语言模型。",
"天空是蓝色的,阳光灿烂。",
"人工智能正在改变世界。",
"Python是一种流行的编程语言。"

完整Case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

from openai import OpenAI
#pip install numpy
from numpy import dot
from numpy.linalg import norm
client = OpenAI()

#定义调用Embedding API的函数
def get_embedding(text):
response = client.embeddings.create(
input=text,
model="text-embedding-ada-002"
)
return response.data[0].embedding

def cosine_similarity(vec1,vec2):
#计算并返回两个向量之间的余弦相似度,公式为:两个向量的点积除以它们范数的乘积。
return dot(vec1 , vec2) / (norm(vec1) * norm(vec2))

# 定义一个函数search_documents,该函数接受一个查询字符串query和一个文档列表documents作为输入。
def search_documents(query,documents):
#调用get_embedding函数生成查询字符串的嵌入向量query_embedding。
query_embedding = get_embedding(query)
#对每个文档调用get_embedding函数生成文档的嵌入向量,存储在document_embeddings列表中。
document_embeddings = [get_embedding(doc) for doc in documents]
#计算查询嵌入向量与每个文档嵌入向量之间的余弦相似度,存储在similarities列表中
similarities = [cosine_similarity(query_embedding,doc_embedding) for doc_embedding in document_embeddings]
#找到相似度最高的文档的索引most_similar_index。
most_similar_index = similarities.index(max(similarities))
#返回相似度最高的文档和相似度得分。
return documents[most_similar_index],max(similarities)


#测试文本搜索功能
if __name__=="__main__":
documents = [
"OpenAI的ChatGPT,是一个强大的语言模型。",
"天空是蓝色的,阳光灿烂。",
"人工智能正在改变世界。",
"Python是一种流行的编程语言。"
]
query="天空是什么颜色的?"

most_similar_document,similarity_score = search_documents(query,documents)

print(f"最相似的文档:{most_similar_document}")
print(f"相似性得分:{similarity_score}")

Dify构建智能体

Posted on 2025-06-23

这里部署社区版本dify,可以参考这个文档 Deploy with Docker Compose - Dify Docs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
git clone https://github.com/langgenius/dify.git --branch 0.15.8
cd /volume1/docker/dify/docker
cp .env.example .env

# 求nginx暴漏端口
EXPOSE_NGINX_PORT=8083
EXPOSE_NGINX_SSL_PORT=4143

# 提前创建好目录
mkdir -p /volume1/docker/dify/docker/volumes/redis/data
mkdir -p /volume1/docker/dify/docker/volumes/db/dat
mkdir -p /volume1/docker/dify/docker/volumes/db/data
mkdir -p /volume1/docker/dify/docker/volumes/weaviate
mkdir -p /volume1/docker/dify/docker/volumes/db/data
mkdir -p /volume1/docker/dify/docker/volumes/app/storage
mkdir -p /volume1/docker/dify/docker/volumes/certbot/conf
mkdir -p /volume1/docker/dify/docker/volumes/certbot/www
mkdir -p /volume1/docker/dify/docker/volumes/certbot/conf/live

# 启动docker
docker-compose up -d

访问 localhost:8083/install 等待安装

设置好管理员账号即可正常使用localhost:8083/apps

工作流

我们以翻译机器人为例演示工作流的使用。

创建一个空白应用

image-20250623173544724

填写相应信息

image-20250623173631087

构造简单工作流整体链路

image-20250623173658904

在开始节点新增 [input]和[lang]变量,用来接受用户的要翻译的文本,和要翻译成的目标语言。

image-20250623173755291

设置LLM大模型,需要注意的是SYSTEM prompt可以点击✨动态生成,引用上游变量可以用大括号{}。USER prompt填写用户输入的Input内容即可。

image-20250623173825862

结束时将大模型内容输出出来。

image-20250623174036300

Agent智能体构建

智能体中可以包含多个工作流,下面需要将上面的工作流嵌入到Agent智能体中。

image-20250623174153810

后续点击发布即可

量化示意图

Posted on 2025-04-24

image-20250424191440341

image-20250424191506927

image-20250424191534518

image-20250424191549179

image-20250424191601872

架构设计-行情

Posted on 2025-04-14

借鉴LSM-Tree的设计思路,先将数据写入缓存池,在周期性写入到CSV

image-20250414092200176

写入策略:

  1. 当内存满>n时,将内容溢写入磁盘
  2. 当时间满>s时,将内存溢写入磁盘

白漂个大厂商的大模型产品

Posted on 2025-03-12

这里我们以硅基流动为例,演示白漂路径。

Cherry Studio提供统一的API入口,不管你是用DeepSeek,还是用OpenAI,这里提供统一的操作入口。下载地址https://nas.yihao.de/sharing/QqHS6F0nY

获取API密钥

安装好APP,到【模型服务】这里,可以看到【API密钥】下面有一个【点击这里获取密钥】点击

到硅基流动官网注册一个帐号,到API 密钥复制,粘贴到上图空白处

image-20250312150907203

使用

到助手,简单测试一下,能否直接使用,找到Qwen 2.5-7B-Instruct ,发送消息即可。

image-20250312151139469

模型

模型决定了问答的质量,市面上有非常多的模型,HuggingFace是模型开源库,里面提供大量的开源模型https://huggingface.co/

白漂模型

要用就用白漂模型,也是够用了。进入硅基流动官网

在【模型广场】-> 【筛选】-> 【只看免费】,找到对应的模型名称,这里以【deepseek-ai/DeepSeek-R1-Distill-Qwen-7B】为例子

image-20250312151347958

到APP中,模型服务->硅基流动->管理 , 粘贴对应的名称并搜索,点击➕添加

image-20250312151609166

之后到助手中,问答的时候选择添加的模型即可

image-20250312151732672

地铁

Posted on 2025-03-07

dt

Hikyuu量化交易二

Posted on 2025-01-16

续上篇文章,第二个小例子

一、策略分析

原始描述

建仓条件:expma周线exp1跟exp2金叉向上使用使用 B=50% 的资金买入股票,建仓成功后,卖出条件才能起作用

卖出条件S1:expma日线exp1和exp2死叉向下时卖出持仓股 S=50%

买入条件B1:expma日线exp1和exp2金叉向上时买入股票数为S(卖出条件S1卖出股数)

S1和B1就这样循环

清仓条件为:expma周线exp1和exp2死叉时

策略分析

市场环境:无

系统有效性:周线EMA1(快线)和EMA2(慢线)金叉向上直到两者死叉,系统有效时建立初始仓位

信号指示器:

  • 买入:日线EMA1(快线)和EMA2(慢线)金叉向上
  • 卖出:日线EMA1(快线)和EMA2(慢线)死叉向下

止损/止盈:无

资金管理:

  • 初次建仓:使用50%的资金
  • 买入:初次建仓时持股数的50%
  • 卖出:初次建仓时持股数的50%

盈利目标:无

二、实现系统部件

自定义系统有效性策略

In [2]:

1
2
3
4
5
6
7
8
9
def getNextWeekDateList(week):
from datetime import timedelta
py_week = week.datetime()
next_week_start = py_week + timedelta(days = 7 - py_week.weekday())
next_week_end = next_week_start + timedelta(days=5)
return get_date_range(Datetime(next_week_start), Datetime(next_week_end))
#ds = getNextWeekDateList(Datetime(201801010000))
#for d in ds:
# print(d)

In [3]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def DEMO_CN(self):
""" DIF > DEA 时,系统有效
参数:
fast_n:周线dif窗口
slow_n: 周线dea窗口
"""
k = self.to
if (len(k) <= 10):
return

#-----------------------------
# 周线
#-----------------------------
week_q = Query(k[0].datetime, k[-1].datetime, ktype=Query.WEEK)
week_k = k.get_stock().get_kdata(week_q)

n1 = self.get_param("week_macd_n1")
n2 = self.get_param("week_macd_n2")
n3 = self.get_param("week_macd_n3")
m = MACD(CLOSE(week_k), n1, n2, n3)
fast = m.get_result(0)
slow = m.get_result(1)

x = fast > slow
for i in range(x.discard, len(x)-1):
if (x[i] >= 1.0):
#需要被扩展到日线(必须是后一周)
date_list = getNextWeekDateList(week_k[i].datetime)
for d in date_list:
self._add_valid(d)

自定义信号指示器

In [4]:

1
#这个例子不需要,已经有内建的SG_Cross函数可直接使用

自定义资金管理策略

In [5]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class DEMO_MM(MoneyManagerBase):
"""
初次建仓:使用50%的资金
买入:初次建仓时持股数的50%
卖出:初次建仓时持股数的50%
"""
def __init__(self):
super(DEMO_MM, self).__init__("MACD_MM")
self.set_param("init_position", 0.5) #自定义初始仓位参数,占用资金百分比
self.next_buy_num = 0

def _reset(self):
self.next_buy_num = 0
#pass

def _clone(self):
mm = DEMO_MM()
mm.next_buy_num = self.next_buy_num
#return DEMO_MM()

def _get_buy_num(self, datetime, stk, price, risk, part_from):
tm = self.tm
cash = tm.current_cash

#如果信号来源于系统有效条件,建立初始仓位
if part_from == System.Part.CONDITION:
#return int((cash * 0.5 // price // stk.atom) * stk.atom) #MoneyManagerBase其实已经保证了买入是最小交易数的整数
self.next_buy_num = 0 #清理掉上一周期建仓期间滚动买卖的股票数
return int(cash * self.get_param("init_position") // price)

#非初次建仓,买入同等数量
return self.next_buy_num

def _getSellNumber(self, datetime, stk, price, risk, part_from):
tm = self.tm
position = tm.get_position(datetime, stk)
current_num = int(position.number * 0.5)

#记录第一次卖出时的股票数,以便下次以同等数量买入
if self.next_buy_num == 0:
self.next_buy_num = current_num

return current_num #返回类型必须是整数

三、构建并运行系统

修改设定公共参数

每个系统部件以及TradeManager都有自己的公共参数会影响系统运行,具体可以查看帮助及试验。

比如:这个例子当前使用系统有效条件进行初始建仓,那么必须设置系统公共参数cn_open_position为True。否则,没有建立初始仓位的话,后续没有卖出,不会有任何交易。

In [6]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#System参数
#delay=True #(bool) : 是否延迟到下一个bar开盘时进行交易
#delay_use_current_price=True #(bool) : 延迟操作的情况下,是使用当前交易时bar的价格计算新的止损价/止赢价/目标价还是使用上次计算的结果
#max_delay_count=3 #(int) : 连续延迟交易请求的限制次数
#tp_monotonic=True #(bool) : 止赢单调递增
#tp_delay_n=3 #(int) : 止盈延迟开始的天数,即止盈策略判断从实际交易几天后开始生效
#ignore_sell_sg=False #(bool) : 忽略卖出信号,只使用止损/止赢等其他方式卖出
#ev_open_position=False #(bool): 是否使用市场环境判定进行初始建仓

cn_open_position=True #(bool): 是否使用系统有效性条件进行初始建仓

#MoneyManager公共参数
#auto-checkin=False #(bool) : 当账户现金不足以买入资金管理策略指示的买入数量时,自动向账户中补充存入(checkin)足够的现金。
#max-stock=20000 #(int) : 最大持有的证券种类数量(即持有几只股票,而非各个股票的持仓数)
#disable_ev_force_clean_position=False #(bool) : 禁用市场环境失效时强制清仓
#disable_cn_force_clean_position=False #(bool) : 禁用系统有效条件失效时强制清仓

设定私有参数及待测试标的

In [7]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#账户参数
init_cash = 500000 #账户初始资金
init_date = '1990-1-1' #账户建立日期

#信号指示器参数
week_n1 = 12
week_n2 = 26
week_n3 = 9

#选定标的,及测试区间
stk = sm['sz000002']

#如果是同一级别K线,可以使用索引号,使用了不同级别的K线数据,建议还是使用日期作为参数
#另外,数据量太大的话,matplotlib绘图会比较慢
start_date = Datetime('2016-01-01')
end_date = Datetime()

构建系统实例

In [8]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#创建模拟交易账户进行回测,初始资金30万
my_tm = crtTM(date=Datetime(init_date), init_cash = init_cash)

#创建系统实例
my_sys = SYS_Simple()

my_sys.set_param("cn_open_position", cn_open_position)

my_sys.tm = my_tm
my_cn = crtCN(DEMO_CN,
{'week_macd_n1': week_n1, 'week_macd_n2': week_n2, 'week_macd_n3': week_n3},
'DEMO_CN')
my_sys.cn = my_cn
my_sys.sg = SG_Cross(EMA(C, n=week_n1), EMA(C, n=week_n2))
my_mm = DEMO_MM()
my_sys.mm = my_mm

运行系统

In [9]:

1
2
3
4
5
6
7
q = Query(start_date, end_date, ktype=Query.DAY)
my_sys.run(stk, q)

#将交易记录及持仓情况,保存在临时目录,可用Excel查看
#临时目录一般设置在数据所在目录下的 tmp 子目录
#如果打开了excel记录,再次运行系统前,记得先关闭excel文件,否则新的结果没法保存
my_tm.tocsv(sm.tmpdir())

四、查看资金曲线及绩效统计

In [10]:

1
2
3
4
#绘制资金收益曲线
x = my_tm.get_profit_curve(stk.get_datetime_list(q), Query.DAY)
#x = my_tm.getFundsCurve(stk.getDatetimeList(q), KQuery.DAY) #资金净值曲线
PRICELIST(x).plot()

image-20250116142158838

In [11]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#回测统计
per = Performance()
print(per.report(my_tm, Datetime.now()))
帐户初始金额: 500000.00
累计投入本金: 500000.00
累计投入资产: 0.00
累计借入现金: 0.00
累计借入资产: 0.00
累计红利: 35609.57
现金余额: 512542.57
未平仓头寸净值: 0.00
当前总资产: 512542.57
已平仓交易总成本: 0.00
已平仓净利润总额: 12542.57
单笔交易最大占用现金比例%: 49.99
交易平均占用现金比例%: 49.85
已平仓帐户收益率%: 2.51
帐户年复合收益率%: 0.32
帐户平均年收益率%: 0.33
赢利交易赢利总额: 226235.57
亏损交易亏损总额: -213693.00
已平仓交易总数: 14.00
赢利交易数: 7.00
亏损交易数: 7.00
赢利交易比例%: 50.00
赢利期望值: 895.90
赢利交易平均赢利: 32319.37
亏损交易平均亏损: -30527.57
平均赢利/平均亏损比例: 1.06
净赢利/亏损比例: 1.06
最大单笔赢利: 140710.57
最大单笔盈利百分比%: 56.58
最大单笔亏损: -54740.00
最大单笔亏损百分比%: -18.85
赢利交易平均持仓时间: 39.86
赢利交易最大持仓时间: 105.00
亏损交易平均持仓时间: 74.86
亏损交易最大持仓时间: 161.00
空仓总时间: 2012.00
空仓时间/总时间%: 71.00
平均空仓时间: 143.00
最长空仓时间: 431.00
最大连续赢利笔数: 2.00
最大连续亏损笔数: 3.00
最大连续赢利金额: 142426.57
最大连续亏损金额: -105390.00
R乘数期望值: 0.01
交易机会频率/年: 1.82
年度期望R乘数: 0.02
赢利交易平均R乘数: 0.12
亏损交易平均R乘数: -0.10
最大单笔赢利R乘数: 0.57
最大单笔亏损R乘数: -0.19
最大连续赢利R乘数: 0.29
最大连续亏损R乘数: -0.19

五、或许想看下图形

In [12]:

1
my_sys.performance()

image-20250116142141416

六、或许想看看所有股票的情况

In [13]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import pandas as pd
def calTotal(blk, q):
per = Performance()
s_name = []
s_code = []
x = []
for stk in blk:
my_sys.run(stk, q)
per.statistics(my_tm, Datetime.now())
s_name.append(stk.name)
s_code.append(stk.market_code)
x.append(per["当前总资产"])
return pd.DataFrame({'代码': s_code, '股票': s_name, '当前总资产': x})

%time data = calTotal(blocka, q)
CPU times: total: 4.98 s
Wall time: 29.2 s

In [14]:

1
2
3
#保存到CSV文件
#data.to_csv(sm.tmpdir() + '/统计.csv')
data[:10]

Out[14]:

代码 股票 当前总资产
0 SH600605 汇通能源 778089.17
1 SH600606 绿地控股 459330.60
2 SH603272 联翔股份 480224.00
3 SH600354 敦煌种业 575339.00
4 SZ300359 全通教育 441039.85
5 SZ000725 京东方A 465180.59
6 BJ838163 方大新材 519824.00
7 SZ300358 楚天科技 496350.30
8 SH600355 精伦电子 390633.00
9 SH603273 天元智能 543317.00

Hikyuu - Quant Framework

Posted on 2025-01-16

Hikyuu Quant Framework是基于C++/Python的高性能开源量化交易研究框架,用于策略分析及回测(目前用于国内A股市场)。其核心思想基于当前成熟的系统化交易方法,将整个系统化交易抽象为由市场环境判断策略、系统有效条件、信号指示器、止损/止盈策略、资金管理策略、盈利目标策略、移滑价差算法七大组件,你可以分别构建这些组件的策略资产库,在实际研究中对它们自由组合来观察系统的有效性、稳定性以及单一种类策略的效果。

下面用一个小例子进行探索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 如果 python 版本 >3.12 ,请将下行注释掉,否则 matplotlib 不会显示图像
%matplotlib inline
%time from hikyuu.interactive import *
iodog.open()
2024-12-07 00:21:52,164 [INFO] hikyuu version: 2.2.3_202412040035_RELEASE_macosx_arm64 [<module>] (/Users/fasiondog/workspace/hikyuu/hikyuu/__init__.py:97) [hikyuu::hku_info]
2024-12-07 00:21:57,486 [WARNING] Matplotlib is building the font cache; this may take a moment. [matplotlib.font_manager::<lambda>]
2024-12-07 00:21:59.835 [HKU-I] - Using SQLITE3 BaseInfoDriver (BaseInfoDriver.cpp:57)
2024-12-07 00:21:59.838 [HKU-I] - Loading market information... (StockManager.cpp:454)
2024-12-07 00:21:59.838 [HKU-I] - Loading stock type information... (StockManager.cpp:472)
2024-12-07 00:21:59.838 [HKU-I] - Loading stock information... (StockManager.cpp:374)
2024-12-07 00:21:59.899 [HKU-I] - Loading stock weight... (StockManager.cpp:490)
2024-12-07 00:21:59.995 [HKU-I] - Loading block... (StockManager.cpp:113)
2024-12-07 00:22:00.076 [HKU-I] - Loading KData... (StockManager.cpp:117)
2024-12-07 00:22:00.076 [HKU-I] - Preloading all day kdata to buffer ! (StockManager.cpp:153)
2024-12-07 00:22:00.077 [HKU-I] - 0.24s Loaded Data. (StockManager.cpp:125)
CPU times: user 756 ms, sys: 255 ms, total: 1.01 s
Wall time: 8.28 s

一、策略分析

原始描述

买入条件:周线MACD零轴下方底部金叉买入30%

卖出条件:日线级别 跌破 20日线 卖出50%持仓

策略分析

市场环境:无

系统有效性:无

信号指示器:

  • 买入信号:周线MACD零轴下方底部金叉,即周线的DIF>DEA金叉时买入(快线:DIF,慢线DEA)
  • 卖出信号:日线级别 跌破 20日均线

止损/止盈:无

资金管理:

  • 买入:30% (不明确,暂且当做当前现金的30%)
  • 卖出:已持仓股票数的50%

盈利目标:

移滑价差:

二、实现系统部件

定义信号指示器

In [2]:

1
2
3
4
5
6
def getNextWeekDate(week):
"""获取指定日期的下一周周一日期"""
from datetime import timedelta
py_week = week.datetime()
next_week_start = py_week + timedelta(days = 7 - py_week.weekday())
return Datetime(next_week_start)

In [3]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def DEMO_SG(self, k):
"""
买入信号:周线MACD零轴下方底部金叉,即周线的DIF>DEA金叉时买入
卖出信号:日线级别 跌破 20日均线

参数:
week_macd_n1:周线dif窗口
week_macd_n2: 周线dea窗口
week_macd_n3: 周线macd平滑窗口
day_n: 日均线窗口
"""
if (len(k) == 0):
return

stk = k.get_stock()

#-----------------------------
#计算日线级别的卖出信号
#-----------------------------
day_c = CLOSE(k)
day_ma = MA(day_c, self.get_param("day_n"))
day_x = day_c < day_ma #收盘价小于均线
for i in range(day_x.discard, len(day_x)):
if day_x[i] >= 1.0:
self._add_sell_signal(k[i].datetime)

#-----------------------------
#计算周线级别的买入信号
#-----------------------------
week_q = Query(k[0].datetime, k[-1].datetime.next_day(), ktype=Query.WEEK)
week_k = k.get_stock().get_kdata(week_q)

n1 = self.get_param("week_macd_n1")
n2 = self.get_param("week_macd_n2")
n3 = self.get_param("week_macd_n3")
m = MACD(CLOSE(week_k), n1, n2, n3)
fast = m.get_result(1)
slow = m.get_result(2)

discard = m.discard if m.discard > 1 else 1
for i in range(discard, len(m)):
if (fast[i-1] < slow[i-1] and fast[i] > slow[i]):
#当周计算的结果,只能作为下周一的信号
self._add_buy_signal(week_k[i].datetime.next_week())

定义资金管理策略

In [4]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class DEMO_MM(MoneyManagerBase):
"""
买入:30% (不明确,暂且当做当前现金的30%)
卖出:已持仓股票数的50%
"""
def __init__(self):
super(DEMO_MM, self).__init__("MACD_MM")

def _reset(self):
pass

def _clone(self):
return DEMO_MM()

def _get_buy_num(self, datetime, stk, price, risk, part_from):
tm = self.tm
cash = tm.current_cash

#可以不用考虑最小交易单位的问题,已经自动处理
# return int(cash*0.3/price) #返回类型必须是int
return cash / price

def _get_sell_num(self, datetime, stk, price, risk, part_from):
tm = self.tm
position = tm.get_position(datetime, stk)
total_num = position.number
num = int(total_num * 0.5)
return num if num >= 100 else 0

三、构建并运行系统

设定系统参数

In [5]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#账户参数
init_cash = 100000 #账户初始资金
init_date = Datetime('1990-1-1') #账户建立日期

#信号指示器参数
week_n1 = 12
week_n2 = 26
week_n3 = 9
day_n = 20

#选定标的,及测试区间
stk = sm['sz000001']
start_date = Datetime('2017-01-01') #如果是同一级别K线,可以使用索引号,使用了不同级别的K线数据,建议还是使用日期作为参数
end_date = Datetime()

构建系统实例

In [6]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#创建账户
my_tm = crtTM(date=init_date, init_cash = init_cash, cost_func=TC_FixedA())

#创建系统实例
my_sys = SYS_Simple()

#绑定账户
my_sys.tm = my_tm

#绑定信号指示器
# !注意
# 受限与 pybind11 的限制,这里不能直接使用 my_sys.sg = crtSG( 或 my_sys.mm = DEMO_MM() , 需要先生成 Python 对象的实例再赋值
my_sg = crtSG(DEMO_SG,
{'week_macd_n1': week_n1, 'week_macd_n2': week_n2, 'week_macd_n3': week_n3, 'day_n': day_n},
'DEMO_SG')
my_sys.sg = my_sg
my_sys.sg.set_param('alternate', False)

#绑定资金管理策略
my_mm = DEMO_MM()
my_sys.mm = my_mm

运行系统

In [7]:

1
2
3
4
5
6
7
8
iodog.close()
q = Query(start_date, end_date, ktype=Query.DAY)
my_sys.run(stk, q)

#将交易记录及持仓情况,保存在临时目录,可用Excel查看
#临时目录一般设置在数据所在目录下的 tmp 子目录
#如果打开了excel记录,再次运行系统前,记得先关闭excel文件,否则新的结果没法保存
my_tm.tocsv(sm.tmpdir())

四、查看资金曲线及绩效统计

In [8]:

1
2
3
4
5
#绘制资金收益曲线(净收益)
x = my_tm.get_profit_curve(stk.get_datetime_list(q), Query.DAY)
#x = my_tm.getFundsCurve(stk.getDatetimeList(q), KQuery.DAY) #总资产曲线
x = PRICELIST(x)
x.plot()

image-20250116141650394

In [9]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#回测统计
per = Performance()
print(per.report(my_tm, Datetime.now()))
帐户初始金额: 100000.00
累计投入本金: 100000.00
累计投入资产: 0.00
累计借入现金: 0.00
累计借入资产: 0.00
累计红利: 3598.40
现金余额: 77807.46
未平仓头寸净值: 1212.64
当前总资产: 79020.10
已平仓交易总成本: 0.00
已平仓净利润总额: 0.00
单笔交易最大占用现金比例%: 99.90
交易平均占用现金比例%: 99.23
已平仓帐户收益率%: 0.00
帐户年复合收益率%: -3.11
帐户平均年收益率%: -2.81
赢利交易赢利总额: 0.00
亏损交易亏损总额: 0.00
已平仓交易总数: 0.00
赢利交易数: 0.00
亏损交易数: 0.00
赢利交易比例%: 0.00
赢利期望值: 0.00
赢利交易平均赢利: 0.00
亏损交易平均亏损: 0.00
平均赢利/平均亏损比例: 0.00
净赢利/亏损比例: 0.00
最大单笔赢利: 0.00
最大单笔盈利百分比%: 0.00
最大单笔亏损: 0.00
最大单笔亏损百分比%: 0.00
赢利交易平均持仓时间: 0.00
赢利交易最大持仓时间: 0.00
亏损交易平均持仓时间: 0.00
亏损交易最大持仓时间: 0.00
空仓总时间: 2721.00
空仓时间/总时间%: 100.00
平均空仓时间: 2721.00
最长空仓时间: 2720.00
最大连续赢利笔数: 0.00
最大连续亏损笔数: 0.00
最大连续赢利金额: 0.00
最大连续亏损金额: 0.00
R乘数期望值: 0.00
交易机会频率/年: 0.00
年度期望R乘数: 0.00
赢利交易平均R乘数: 0.00
亏损交易平均R乘数: 0.00
最大单笔赢利R乘数: 0.00
最大单笔亏损R乘数: 0.00
最大连续赢利R乘数: 0.00
最大连续亏损R乘数: 0.00

In [10]:

1
my_sys.performance()

image-20250116141625079

五、或许想看下图形

In [11]:

1
2
my_sys.plot()
MA(CLOSE(my_sys.to), 20).plot(new=False)

image-20250116141550061

六、或许想看看所有股票的情况

In [12]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import pandas as pd
def calTotal(blk, q):
per = Performance()
s_name = []
s_code = []
x = []
for stk in blk:
my_sys.run(stk, q)
per.statistics(my_tm, Datetime.now())
s_name.append(stk.name)
s_code.append(stk.market_code)
x.append(per["当前总资产"])
return pd.DataFrame({'代码': s_code, '股票': s_name, '当前总资产': x})

%time data = calTotal(blocka, q)
CPU times: user 16.1 s, sys: 1.58 s, total: 17.7 s
Wall time: 16.7 s

In [13]:

1
2
3
#保存到CSV文件
#data.to_csv(sm.tmpdir() + '/统计.csv')
data[:10]

Out[13]:

代码 股票 当前总资产
0 SH601003 柳钢股份 66414.81
1 SH603180 金牌家居 65716.52
2 SZ000548 湖南投资 63616.49
3 SH600159 大龙地产 40364.84
4 SZ002099 海翔药业 53875.08
5 SH600732 爱旭股份 198582.34
6 SH603127 昭衍新药 131866.78
7 SZ002953 日丰股份 69972.42
8 SH603758 秦安股份 72336.15
9 SZ002962 五方光电 54827.43
12…6>

58 posts
© 2025 Hoey