You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现简单的二元序列(1/-1)预测?

二元序列(1/-1)的简单Python预测方案

以下是几种比ARIMA更易实现的简单方案,按复杂度从低到高排序:

1. 历史频率统计法

直接统计历史序列中1和-1的出现次数,选择出现更频繁的作为下一个预测值;若次数相等,默认返回最后一个元素。

def predict_by_frequency(sequence):
    count_1 = sequence.count(1)
    count_neg1 = sequence.count(-1)
    if count_1 > count_neg1:
        return 1
    elif count_neg1 > count_1:
        return -1
    else:
        return sequence[-1] if sequence else None

# 测试示例
history = [1, -1, 1, 1, 1, -1, -1, 1]
print(predict_by_frequency(history))  # 输出1(1出现5次,-1出现3次)

2. 最近模式匹配法

指定一个窗口大小,提取序列最后window_size个元素作为匹配模式,在历史数据中查找所有相同的模式,统计模式后跟随最多的1/-1作为预测值;若历史数据不足或无匹配模式,用频率法兜底。

def predict_by_recent_pattern(sequence, window_size=2):
    if len(sequence) < window_size + 1:
        return predict_by_frequency(sequence)
    
    target_pattern = sequence[-window_size:]
    candidates = []
    
    for i in range(len(sequence) - window_size):
        if sequence[i:i+window_size] == target_pattern:
            candidates.append(sequence[i+window_size])
    
    if not candidates:
        return sequence[-1]
    
    count_1 = candidates.count(1)
    count_neg1 = candidates.count(-1)
    return 1 if count_1 >= count_neg1 else -1

# 测试示例
history = [1, -1, 1, 1, 1, -1, -1, 1]
print(predict_by_recent_pattern(history, window_size=2))  # 输出1(最后模式[-1,1]在历史中仅出现1次,后续为1)

3. 简单逻辑回归法

用滑动窗口将序列转换为特征-标签对,训练一个轻量的逻辑回归模型来预测下一个值。相比前两种方法,它能捕捉序列中的简单线性依赖关系,且实现难度远低于ARIMA。

from sklearn.linear_model import LogisticRegression
import numpy as np

def create_features(sequence, window_size=3):
    X, y = [], []
    # 将-1转换为0适配逻辑回归的二分类输出
    for i in range(len(sequence) - window_size):
        X.append(sequence[i:i+window_size])
        y.append(1 if sequence[i+window_size] == 1 else 0)
    return np.array(X), np.array(y)

def predict_by_logistic_regression(sequence, window_size=3):
    if len(sequence) < window_size + 1:
        return predict_by_frequency(sequence)
    
    X, y = create_features(sequence, window_size)
    model = LogisticRegression()
    model.fit(X, y)
    
    # 用最后一组窗口特征预测
    last_window = np.array(sequence[-window_size:]).reshape(1, -1)
    pred_label = model.predict(last_window)[0]
    return 1 if pred_label == 1 else -1

# 测试示例
history = [1, -1, 1, 1, 1, -1, -1, 1]
print(predict_by_logistic_regression(history))  # 输出根据训练结果而定,示例中大概率为1

方案选择建议

  • 若序列无明显规律,优先用历史频率统计法;
  • 若序列存在重复局部模式,调整窗口大小用最近模式匹配法;
  • 若序列有弱线性依赖,且希望模型自动捕捉规律,选简单逻辑回归法。

内容的提问来源于stack exchange,提问作者Jinho Choi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:20:42