告别手动调参!用Python从零实现一个洗衣机模糊控制器(附完整代码)

在智能家居项目中,精确控制家电运行参数往往需要复杂的数学模型和大量调试。而模糊控制技术提供了一种更接近人类思维的解决方案——通过模拟人的经验决策过程,用简单的规则实现智能控制。本文将带你用纯Python实现一个洗衣机洗涤时间模糊控制器,无需依赖MATLAB等专业工具,代码可直接集成到树莓派等嵌入式系统中。

1. 模糊控制基础与洗衣机场景设计

模糊控制的核心在于用"部分属于"代替传统布尔逻辑的"非此即彼"。对于洗衣机场景,我们需要处理两个输入变量(污泥程度、油脂程度)和一个输出变量(洗涤时间)。每个变量都被划分为几个模糊集合:

  • 污泥程度 :少(SD)、中(MD)、多(LD)
  • 油脂程度 :少(NG)、中(MG)、多(LG)
  • 洗涤时间 :很短(VS)、短(S)、中(M)、长(L)、很长(VL)

这些模糊集合通过 隶属度函数 定义,常见的有三角形、梯形和高斯函数。我们选择计算高效的三角形函数:

import numpy as np

def trimf(x, params):
    """三角形隶属度函数
    params: [a, b, c] 三个顶点横坐标
    """
    a, b, c = params
    return np.maximum(0, np.minimum((x-a)/(b-a), (c-x)/(c-b)))

2. 构建模糊推理系统

2.1 定义输入输出变量

我们设定所有变量的论域范围为[0,100],洗涤时间映射到[0,120]分钟:

# 污泥隶属函数参数
sludge_params = {
    'SD': [0, 0, 50],  # 少
    'MD': [0, 50, 100], # 中 
    'LD': [50, 100, 100] # 多
}

# 油脂隶属函数参数
grease_params = {
    'NG': [0, 0, 50],
    'MG': [0, 50, 100],
    'LG': [50, 100, 100]
}

# 洗涤时间隶属函数参数
wash_time_params = {
    'VS': [0, 0, 30],
    'S': [0, 30, 60],
    'M': [30, 60, 90],
    'L': [60, 90, 120],
    'VL': [90, 120, 120]
}

2.2 模糊规则库设计

根据人类操作经验,我们建立9条模糊规则:

规则编号 条件部分 结论部分
1 IF 污泥少 AND 油脂少 THEN 时间很短
2 IF 污泥少 AND 油脂中 THEN 时间短
3 IF 污泥少 AND 油脂多 THEN 时间中等
... ... ...
9 IF 污泥多 AND 油脂多 THEN 时间很长

在代码中用字典实现规则库:

rules = [
    {'input': ['SD', 'NG'], 'output': 'VS'},
    {'input': ['SD', 'MG'], 'output': 'S'},
    {'input': ['SD', 'LG'], 'output': 'M'},
    # ... 其他规则
]

3. 实现模糊推理引擎

3.1 模糊化处理

将精确输入值转换为各模糊集合的隶属度:

def fuzzify(x, params_dict):
    """计算输入值对各模糊集合的隶属度"""
    result = {}
    for name, params in params_dict.items():
        result[name] = trimf(x, params)
    return result

# 示例:污泥值为60时的模糊化
sludge_60 = fuzzify(60, sludge_params)
# 输出: {'SD': 0.0, 'MD': 0.8, 'LD': 0.2}

3.2 规则评估与聚合

使用Mamdani推理方法,采用min-max运算:

def evaluate_rules(sludge_degree, grease_degree, rules):
    """评估所有适用规则"""
    outputs = {}
    for rule in rules:
        # 取前提条件的最小值
        premise_strength = min(
            sludge_degree[rule['input'][0]],
            grease_degree[rule['input'][1]]
        )
        # 聚合到输出变量
        if rule['output'] in outputs:
            outputs[rule['output']] = max(outputs[rule['output']], premise_strength)
        else:
            outputs[rule['output']] = premise_strength
    return outputs

4. 去模糊化与结果获取

采用重心法(COG)将模糊输出转换为精确值:

def defuzzify(output_degrees, time_params, resolution=100):
    """重心法去模糊化"""
    time_range = np.linspace(0, 120, resolution)
    aggregated = np.zeros_like(time_range)
    
    # 构建聚合隶属函数
    for name, degree in output_degrees.items():
        params = time_params[name]
        mf = trimf(time_range, params)
        aggregated = np.maximum(aggregated, np.minimum(degree, mf))
    
    # 计算重心
    if np.sum(aggregated) == 0:
        return 0
    return np.sum(time_range * aggregated) / np.sum(aggregated)

5. 完整系统集成与测试

将所有组件封装为FuzzyWashController类:

class FuzzyWashController:
    def __init__(self):
        self.sludge_params = sludge_params
        self.grease_params = grease_params
        self.time_params = wash_time_params
        self.rules = rules
        
    def compute_wash_time(self, sludge, grease):
        # 模糊化
        sludge_degree = fuzzify(sludge, self.sludge_params)
        grease_degree = fuzzify(grease, self.grease_params)
        
        # 规则评估
        output_degrees = evaluate_rules(sludge_degree, grease_degree, self.rules)
        
        # 去模糊化
        return defuzzify(output_degrees, self.time_params)

# 测试实例
controller = FuzzyWashController()
wash_time = controller.compute_wash_time(60, 70)
print(f"推荐洗涤时间: {wash_time:.1f} 分钟")

6. 性能优化与工程实践

在实际部署中,我们可以通过以下方式提升系统性能:

  1. 预计算加速 :对常见输入组合预先计算并缓存结果
  2. 参数调优 :调整隶属函数形状和规则权重
  3. 硬件加速 :使用Numba等工具编译Python代码
from numba import jit

@jit(nopython=True)
def fast_trimf(x, a, b, c):
    """Numba加速的隶属度函数"""
    return max(0, min((x-a)/(b-a), (c-x)/(c-b)))

模糊控制器的优势在于其易于理解和调整规则,当发现洗涤效果不理想时,只需修改规则库而无需重写整个算法。这种特性使其特别适合快速原型开发和DIY智能家居项目。

更多推荐