资源简介
囚徒困境的演化博弈的python实现,代码可实现演化过程的图像演示,可设置是否可以合作及背叛等条件,如有需要可自行下载,欢迎讨论。
代码片段和文件信息
# -*- coding: utf-8 -*-
# !/usr/bin/python3
import random
from collections import Counter
import matplotlib.pyplot as plt
import sys
import inspect
BETRAY = True
COOPERATE = False
# 定义策略母类
class Alg:
def get_score(self):
if len(self.score)>50:
self.score = [sum(self.score)]
return self.score
def __init__(self):
self.my_history = []
self.their_history = []
self.score = []
def play(self):
“““ @param my_history List of own last choices
@param their_history List of last choices of the other
@return decision {BETRAY SILENT}
“““
raise NotImplementedError
def __repr__(self):
return “{}“.format(type(self).__name__)
def reinit_history(self):
self.my_history = []
self.their_history = []
return self
def partition(ls size):
“““
Returns a new list with elements
of which is a list of certain size.
>>> partition([1 2 3 4] 3)
[[1 2 3] [4]]
“““
return [ls[i:i + size] for i in range(0 len(ls) size)]
def score(A_choice B_choice):
if A_choice == B_choice:
if A_choice == BETRAY:
return (1 1)
return (3 3)
if A_choice == BETRAY:
return (5 0)
return (0 5)
def play(A B):
A_score = 0
B_score = 0
A_choice = A.play(A.my_history B.my_history)
B_choice = B.play(B.my_history A.my_history)
A_score_ B_score_ = score(A_choice B_choice)
A.my_history.append(A_choice)
B.my_history.append(B_choice)
A.their_history.append(B_choice)
B.their_history.append(A_choice)
A.score.append(A_score_)
B.score.append(B_score_)
return (A_score_ B_score_)
# 一期博弈过程,即所有样本随机两两匹配后博弈rounds次
def simulate(persons rounds seed=42):
“““
:param persons: 所有参与人对象列表
:param strategy_score: 不同策略得分,初始均为0
:param seed:
:param rounds: 当前期博弈次数
:return: strategy_score
“““
random.shuffle(persons)
# print (persons)
persons_pairs = partition(persons 2)
# print(partition(persons 2))
for i in range(rounds):
# tmp = []
for pair in persons_pairs:
play(pair[0] pair[1])
# 自我繁殖过程,每隔1期进行一次自我繁殖
def self_reproduction(persons mutation_rate out_rate):
“““
:param persons: 博弈后样本列表
:param mutation_rate: 变异率
:param out_rate: 淘汰率
:return: 自我繁殖后样本列表
“““
mutation_count = int(len(persons) * mutation_rate)
out_count = int(len(persons) * out_rate)
for person in persons:
score_list = [sum(person.get_score()) for person in persons]
persons.sort(key=lambda x: sum(x.get_score()) reverse=True)
# print (persons_sorted)
score_sorted = [sum(person.get_score()) for person in persons]
# 获取淘汰样本及变异样本
out_persons = persons[-out_count:]
random.shuffle(out_persons)
mutation
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 11705 2019-11-06 20:38 run.py
- 上一篇:数据处理程序
- 下一篇:抓取CSDN博客文章的简单爬虫python源码
评论
共有 条评论