36. 理解copy_if算法的正确实现

STL中有11个算法名字包含"copy":

  • copy
  • copy_backward
  • replace_copy
  • reverse_copy
  • replace_copy_if
  • unique_copy
  • remove_copy
  • rotate_copy
  • remove_copy_if
  • partial_sort_copy
  • unitialized_copy

但是STL中却不包括copy_if的实现,如果需要它,必须自己实现。
下面是copy_if的正确实现:

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p)
{
	while (begin != end)
	{
		if (p(*begin)) *destBegin++ == *begin;
		++begin;
	}
	
	return destBegin;
}

下面是SGI STL中copy算法的实现:

template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last, _OutputIter __result, input_iterator_tag, _Distance*)
{
	for (; __first != __last; ++__result, ++__first)
		*__result = *__first;

	return __result;
}

template <class _RandomAccessIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_RandomAccessIter __first, _RandomAccessIter __last, _OutputIter __result, random_access_iterator_tag, _Distance*)
{
	for (_Distance __n = __last - __first; __n > 0; --__n) 
	{
		*__result = *__first;
		++__first;
		++__result;
	}

	return __result;
}

注意,copy、copy_if算法中都没有对__result进行有效性判断(也不法进行判断), 所以调用方必须确保目标位置__result有效,否则会出现未定义行为。

``` class IPSO_EGA: def __init__(self, model, X, y, pop_size=50, max_iter=100): self.model = model self.X = X self.y = y self.pop_size = pop_size self.max_iter = max_iter # 参数维度计算 self.dim = (model.W1.size + model.b1.size + model.W2.size + model.b2.size) # PSO参数 self.w = 0.800 self.c1 = self.c2 = 1.49445 # 初始化种群 self.population = np.random.uniform(-1, 1, (pop_size, self.dim)) self.velocity = np.zeros((pop_size, self.dim)) self.pbest = self.population.copy() self.gbest = self.population[0].copy() # 适应度计算 self.pbest_fit = np.full(pop_size, np.inf) self.gbest_fit = np.inf def _unpack_params(self, params): w1_size = self.model.W1.size b1_size = self.model.b1.size w2_size = self.model.W2.size W1 = params[:w1_size].reshape(self.model.W1.shape) b1 = params[w1_size:w1_size + b1_size] W2 = params[w1_size + b1_size:w1_size + b1_size + w2_size].reshape(self.model.W2.shape) b2 = params[-self.model.b2.size:] return W1, b1, W2, b2 def fitness(self, params): try: W1, b1, W2, b2 = self._unpack_params(params) self.model.W1 = W1 self.model.b1 = b1 self.model.W2 = W2 self.model.b2 = b2 y_pred = self.model.forward(self.X) return mean_squared_error(self.y, y_pred) except: return np.inf # IPSO优化 def pso_update(self): for i in range(self.pop_size): self.velocity[i] = (self.w * self.velocity[i] + self.c1 * np.random.rand() * (self.pbest[i] - self.population[i]) + self.c2 * np.random.rand() * (self.gbest - self.population[i])) self.population[i] += self.velocity[i] # EGA优化 def ga_operate(self): # 选择(锦标赛选择) new_pop = [] for _ in range(self.pop_size): idx = np.random.choice(self.pop_size, 3, replace=False) best_idx = idx[np.argmin([self.fitness(self.population[i]) for i in idx])] new_pop.append(self.population[best_idx]) # 交叉(均匀交叉) for i in range(0, self.pop_size - 1, 2): mask = np.random.rand(self.dim) > 0.5 new_pop[i][mask], new_pop[i + 1][mask] = new_pop[i + 1][mask], new_pop[i][mask] # 变异 for i in range(self.pop_size): if np.random.rand() < 0.1: self.population[i] += np.random.normal(0, 0.1, self.dim) def optimize(self): for epoch in range(self.max_iter): # PSO阶段 self.pso_update() # 评估适应度 for i in range(self.pop_size): fit = self.fitness(self.population[i]) if fit < self.pbest_fit[i]: self.pbest_fit[i] = fit self.pbest[i] = self.population[i].copy() if fit < self.gbest_fit: self.gbest_fit = fit self.gbest = self.population[i].copy() # EGA阶段 self.ga_operate()```帮我生成一个流程图
最新发布
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值