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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
pipeline_tag: text-generation
|
| 12 |
tags:
|
| 13 |
- finance
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# 金融欺诈检测机器人
|
| 17 |
+
|
| 18 |
+
## 使用方式
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
import os
|
| 23 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# 设置模型和数据路径
|
| 30 |
+
MODEL_PATH = "Fintech-Dreamer/FinSynth_model_fraud"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_response(model, tokenizer, instruction, input_text, max_length=2048):
|
| 34 |
+
"""
|
| 35 |
+
使用模型生成回答
|
| 36 |
+
|
| 37 |
+
参数:
|
| 38 |
+
model: 加载的语言模型实例
|
| 39 |
+
tokenizer: 模型对应的分词器
|
| 40 |
+
instruction: 指令部分文本,一般是任务描述
|
| 41 |
+
input_text: 输入文本,一般是需要分析的内容
|
| 42 |
+
max_length: 生成文本的最大长度,默认为2048个token
|
| 43 |
+
|
| 44 |
+
返回:
|
| 45 |
+
prompt: 完整的输入提示词
|
| 46 |
+
response: 模型生成的回答
|
| 47 |
+
"""
|
| 48 |
+
# 构造提示词格式 - 使用特殊标记组织对话形式
|
| 49 |
+
# <|begin of sentence|>标记句子开始,<|User|>和<|Assistant|>分别标记用户和助手角色
|
| 50 |
+
prompt = f"<|begin of sentence|><|User|>{instruction}\n{input_text}<|Assistant|>"
|
| 51 |
+
|
| 52 |
+
# 编码输入,将文本转换为模型可以理解的token序列
|
| 53 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True)
|
| 54 |
+
# 将输入移动到模型所在的设备(CPU或GPU)
|
| 55 |
+
inputs = inputs.to(model.device)
|
| 56 |
+
|
| 57 |
+
# 使用torch.no_grad()避免计算梯度,节省内存并加速推理过程
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
# 调用模型的generate方法生成回答
|
| 60 |
+
outputs = model.generate(
|
| 61 |
+
**inputs,
|
| 62 |
+
max_length=max_length, # 设置生成文本的最大长度
|
| 63 |
+
num_return_sequences=1, # 只返回一个生成序列
|
| 64 |
+
do_sample=True, # 使用采样策略,增加多样性
|
| 65 |
+
temperature=0.6, # 温度参数,控制生成文本的随机性(较低的值使输出更确定)
|
| 66 |
+
top_p=0.95, # 使用nucleus sampling,只考虑概率和超过0.95的token
|
| 67 |
+
pad_token_id=tokenizer.eos_token_id, # 将填充标记设置为结束标记
|
| 68 |
+
use_cache=True, # 使用缓存加速生成过程
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# 将生成的token序列解码为文本
|
| 72 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 73 |
+
|
| 74 |
+
# 提取回答部分(去除提示词部分)
|
| 75 |
+
if "<|Assistant|>" in response:
|
| 76 |
+
response = response.split("<|Assistant|>")[1].strip()
|
| 77 |
+
|
| 78 |
+
return prompt, response
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def process_test_data():
|
| 82 |
+
"""
|
| 83 |
+
处理测试数据集并生成预测结果
|
| 84 |
+
|
| 85 |
+
功能:
|
| 86 |
+
- 加载测试数据集
|
| 87 |
+
- 初始化模型和分词器
|
| 88 |
+
- 对每个测试样本进行预测
|
| 89 |
+
- 输出预测结果
|
| 90 |
+
|
| 91 |
+
返回:
|
| 92 |
+
None,结果直接打印
|
| 93 |
+
"""
|
| 94 |
+
# 加载测试数据
|
| 95 |
+
|
| 96 |
+
# 加载模型和分词器
|
| 97 |
+
print(f"加载模型: {MODEL_PATH}")
|
| 98 |
+
# 加载预训练的分词器,用于将文本转换为token
|
| 99 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 100 |
+
# 加载预训练的语言模型,设置为自动选择设备,使用bfloat16精度以提高性能
|
| 101 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 102 |
+
MODEL_PATH,
|
| 103 |
+
device_map="auto", # 自动选择可用的设备(CPU/GPU)
|
| 104 |
+
torch_dtype=torch.bfloat16, # 使用bfloat16精度,在保持准确性的同时减少内存占用
|
| 105 |
+
use_cache=True, # 启用缓存以提高生成速度
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 设置模型为评估模式,关闭dropout等训练特性,提高推理性能
|
| 109 |
+
model.eval()
|
| 110 |
+
|
| 111 |
+
# 处理每个测试样本
|
| 112 |
+
print("开始生成预测...")
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
# 提取指令和输入文本
|
| 116 |
+
instruction = "Combine your financial knowledge to carefully analyze whether this is a fraudulent transaction,just answer yes or no" # 指令部分,告诉模型要执行的任务
|
| 117 |
+
input_text = "The transaction involves a 20-year-old customer with an income of $0.1, who has been at their current address for 46 months. The request was made 0.03 days ago, and the intended amount is $48.49. The payment type is 'AA', and the email used is from a free provider. The customer's bank account is 6 months old, and they do not have other credit cards. The proposed credit limit is $1500, and the request was made via the internet. The session lasted 3.36 minutes, and the device used had 1 distinct email in the last 8 weeks. The device has no prior fraud records." # 输入文本,需要分析的内容
|
| 118 |
+
|
| 119 |
+
print("\n正在生成预测...")
|
| 120 |
+
|
| 121 |
+
# 调用generate_response函数生成预测
|
| 122 |
+
full_prompt, response = generate_response(model, tokenizer, instruction, input_text)
|
| 123 |
+
|
| 124 |
+
# 打印完整的预测结果,不截断
|
| 125 |
+
print("\n===== 完整输入输出 =====")
|
| 126 |
+
print(f"提示词: {full_prompt}")
|
| 127 |
+
print(f"\n预测结果: {response}")
|
| 128 |
+
|
| 129 |
+
# 简要展示关键结果
|
| 130 |
+
print("\n===== 简要结果 =====")
|
| 131 |
+
# 简单的欺诈判断逻辑:检查输出中是否包含"fraudulent"且不包含"not"
|
| 132 |
+
print(f"预测标签: {'欺诈' if 'fraudulent' in response.lower() and 'not' not in response.lower() else '非欺诈'}")
|
| 133 |
+
print(f"输出长度: {len(response)} 字符")
|
| 134 |
+
|
| 135 |
+
# 以JSON格式输出结果,便于后续处理或保存
|
| 136 |
+
print("\n===== JSON格式 =====")
|
| 137 |
+
result_json = {"prompt": full_prompt, "predict": response}
|
| 138 |
+
print(result_json)
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
# 异常处理,确保一个样本的错误不会导致整个程序崩溃
|
| 142 |
+
print(f"\n处理样本时出错: {str(e)}")
|
| 143 |
+
import traceback
|
| 144 |
+
|
| 145 |
+
traceback.print_exc() # 打印详细错误信息,便于调试
|
| 146 |
+
|
| 147 |
+
print("\n预测完成!")
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
"""
|
| 153 |
+
主函数,程序入口点
|
| 154 |
+
|
| 155 |
+
功能:
|
| 156 |
+
- 启动测试数据处理和预测流程
|
| 157 |
+
"""
|
| 158 |
+
print("===== 模型调用 =====")
|
| 159 |
+
process_test_data()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
main()
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
## 数据集参考
|
| 167 |
+
|
| 168 |
+
[Fintech-Dreamer/FinSynth_data · Datasets at Hugging Face](https://huggingface.co/datasets/Fintech-Dreamer/FinSynth_data)
|
| 169 |
+
|
| 170 |
+
## 前端框架参考
|
| 171 |
+
|
| 172 |
+
[Fintech-Dreamer/FinSynth](https://github.com/Fintech-Dreamer/FinSynth)
|
| 173 |
+
|
| 174 |
+
## 数据处理方式参考
|
| 175 |
+
|
| 176 |
+
[Fintech-Dreamer/FinSynth-Data-Processing](https://github.com/Fintech-Dreamer/FinSynth-Data-Processing)
|
| 177 |
+
|