random.choices(population, weights=None, *, cum_weights=None, k=1)是Python中random子產品提供的一個函數,用于從序列population中随機選擇k個元素,并傳回一個清單。其中,序列population可以是清單、元組、字元串或其他序列類型。另外,weights參數可以指定每個元素被選擇的權重,cum_weights參數可以指定每個元素的累積權重,進而影響元素被選擇的機率。
函數參數說明:
- population:必選參數,表示要從中選擇元素的序列,可以是清單、元組、字元串或其他序列類型。
- weights:可選參數,表示每個元素被選擇的權重,必須是一個與population長度相同的清單。如果不指定該參數,則預設每個元素的權重相等。
- cum_weights:可選參數,表示每個元素的累積權重,必須是一個與population長度相同的清單。如果同時指定了weights和cum_weights參數,則weights參數将被忽略。
- k:可選參數,表示要選擇的元素個數,預設為1。
1、我們使用 random.choices() 從1到6的數字中随機選擇一個數字,以模拟擲骰子的結果。
import random
# 模拟擲骰子
def roll_die(sides):
return random.choices(range(1, sides+1))[0]
# 調用擲骰子函數
sides = 6
result = roll_die(sides)
print(result)
2、random.choices()函數來實作遺傳算法的選擇操作
import random
# 生成初始種群
def generate_population(size, chromosome_length):
population = []
for i in range(size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
return population
# 适應度函數
def fitness(chromosome):
return sum(chromosome)
# 選擇操作
def selection(population, fitnesses):
return random.choices(population, weights=fitnesses, k=2)
# 交叉操作
def crossover(parent1, parent2):
point = random.randint(0, len(parent1) - 1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
# 變異操作
def mutation(individual):
mutation_rate = 0.01
mutation_range = 0.1
if random.random() < mutation_rate:
return [gene + random.uniform(-mutation_range, mutation_range) for gene in individual]
else:
return individual
# 下一代個體生成
def next_generation(population, fitnesses):
new_population = []
for i in range(len(population)):
parent1, parent2 = selection(population, fitnesses)
child1, child2 = crossover(parent1, parent2)
mutated_child1 = mutation(child1)
mutated_child2 = mutation(child2)
new_population.append(max([parent1, parent2, mutated_child1, mutated_child2], key=fitness))
return new_population
# 遺傳算法主函數
def genetic_algorithm(chromosome_length, population_size, generations):
population = generate_population(population_size, chromosome_length)
for i in range(generations):
fitnesses = [fitness(individual) for individual in population]
population = next_generation(population, fitnesses)
return max(population, key=fitness)
# 調用遺傳算法
chromosome_length = 10
population_size = 100
generations = 50
result = genetic_algorithm(chromosome_length, population_size, generations)
print(result)
需要進行選擇、交叉和變異操作,以生成新的一代個體。選擇操作可以使用random.choices()函數來實作,根據适應度大小來确定每個個體被選中的機率
3、投票分類器融合
import random
# 假設有 10 個分類器
classifiers = ["classifier1", "classifier2", "classifier3", "classifier4", "classifier5",
"classifier6", "classifier7", "classifier8", "classifier9", "classifier10"]
# 定義 vote 函數
def vote(classifiers):
predictions = random.choices(classifiers, k=5)
return max(set(predictions), key=predictions.count)
# 調用 vote 函數得到內建預測結果
ensemble_prediction = vote(classifiers)
print("內建預測結果:", ensemble_prediction)