weixin_50878518 2024-10-14 16:52 采纳率: 0%
浏览 64
已结题

速求!商品购买力最优化问题(用遗传算法求解,给出python代码)

问题描述:假设有两间商店,A店有abc三种商品,B店有cdef四种商品,abcdef商品价格分别为432543元,要求每样商品必须购买,即每样商品购买数量大于0,但在A商店购买的商品总数量小于10,在B商店购买的商品总数量小于8,求最优购买力(最小值),用遗传算法怎么优化,给出Python代码

  • 写回答

44条回答 默认 最新

  • 专家-皆知 2024-10-14 17:04
    关注
    获得1.00元问题酬金
    import numpy as np
    import random
    
    # 商品价格
    prices_A = [432, 543, 432]  # A店商品abc的价格
    prices_B = [543, 432, 543, 654]  # B店商品cdef的价格
    
    # 商品数量限制
    max_A = 10
    max_B = 8
    
    # 遗传算法参数
    population_size = 100
    generations = 200
    mutation_rate = 0.1
    
    
    # 适应度函数
    def fitness(individual):
        quantity_A = individual[:3]  # A店的商品数量
        quantity_B = individual[3:]  # B店的商品数量
    
        total_A = sum(quantity_A)
        total_B = sum(quantity_B)
    
        if total_A > max_A or total_B > max_B:
            return float('inf')  # 不满足约束,适应度为无穷大
    
        total_cost = sum(quantity_A[i] * prices_A[i] for i in range(3)) + \
                     sum(quantity_B[i] * prices_B[i] for i in range(4))
    
        return total_cost
    
    
    # 初始化种群
    def initialize_population():
        return [np.random.randint(1, 10, size=7) for _ in range(population_size)]
    
    
    # 选择操作
    def selection(population):
        scores = np.array([fitness(ind) for ind in population])
    
        # 处理适应度为无穷大的个体
        scores[scores == float('inf')] = np.nan  # 将无穷大替换为NaN
        valid_indices = np.where(~np.isnan(scores))[0]  # 有效个体的索引
        valid_scores = scores[~np.isnan(scores)]  # 有效适应度
    
        if len(valid_scores) == 0:
            return random.sample(population, population_size // 2)  # 如果没有有效个体,随机选择
    
        probabilities = np.exp(-valid_scores / np.sum(valid_scores))  # 计算有效个体的概率
        probabilities /= probabilities.sum()  # 归一化
    
        # 确保选择的数量不超过有效个体的数量
        num_to_select = min(population_size // 2, len(valid_indices))
        selected_indices = np.random.choice(valid_indices, size=num_to_select, replace=False, p=probabilities)
        return [population[i] for i in selected_indices]
    
    
    # 交叉操作
    def crossover(parent1, parent2):
        crossover_point = random.randint(0, 6)
        child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
        child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
        return child1, child2
    
    
    # 变异操作
    def mutate(individual):
        if random.random() < mutation_rate:
            mutation_index = random.randint(0, 6)
            individual[mutation_index] = random.randint(1, 10)  # 变异为1到10之间的随机数
    
    
    # 遗传算法主程序
    def genetic_algorithm():
        population = initialize_population()
    
        for generation in range(generations):
            selected = selection(population)
    
            # 检查选中的个体数量
            if len(selected) < 2:
                print("有效个体不足,无法进行交叉操作。")
                break
    
            next_generation = []
    
            while len(next_generation) < population_size:
                parent1, parent2 = random.sample(selected, 2)
                child1, child2 = crossover(parent1, parent2)
                mutate(child1)
                mutate(child2)
                next_generation.extend([child1, child2])
    
            population = next_generation[:population_size]
    
        # 找到最优解
        best_individual = min(population, key=fitness)
        return best_individual, fitness(best_individual)
    
    
    # 运行遗传算法
    best_solution, best_cost = genetic_algorithm()
    print("最优购买方案:", best_solution)
    print("最小总花费:", best_cost)
    
    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 10月22日
  • 赞助了问题酬金100元 10月14日
  • 创建了问题 10月14日