question&solution-1,2

Q.1 vscode相对路径问题

文件结构如下:

————model
	————A.py
		————E(class or func)
	————B.py
		————F(class or func)
	————__init__.py
————utils
	————utilss
		————C.py
			————G(class or func)
————D.py
	————H(class or func)
————train.py

运行A.py

调用B.py中的F

from B import F

调用D.py

import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import D

注意,下图所示方式容易出错

import sys
sys.path.append("..")
import  D
调用D.py中的H时

基于上述,在A.py中写D.H()

调用C.py

import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from utils.utills import C
调用C.py中的G时

基于上述,在A.py中写C.G()

运行D.py

导入A.py

A.py没有调用同级目录下的其他文件(如B.py)

在model下A.py同级新建空的__init__文件,再在D.py文件中写from model import A

A.py又调用B.py文件

在model下A.py同级新建空的__init__文件,再在A.py中写:

import sys
sys.path.append("..")
import model.B as B

from . import B
二选一
然后在D.py文件中写from model import A
不然会报错ModuleNotFoundError: No module named 'B'

A.py又调用C.py文件

在A.py中写from utils.utills import C,因为此时的绝对路径是D

Q2.数据类型的问题

查看模型的两个输出是否相等

直接判断报错

if (out1==out2):
	print("true")

报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous,可能出现情况有:

  1. 将含有两个及以上的布尔值的张量用在了 if 判断条件里:
a = torch.tensor([True, False])
if a:
	print(1)

改为

if a is not None:
    print(1)

需要注意的是,如果 a 只含一个布尔值,则判断不会出现错误:

a = torch.tensor([True])
if a:
    print(1)
  1. 使用交叉熵损失时没有先实例化:
inputs = torch.randn(6, 4)
target = torch.randint(4, (6, ))
loss = nn.CrossEntropyLoss(inputs, target)

应先实例化再计算损失:

criterion = nn.CrossEntropyLoss()
loss = criterion(inputs, target)
  1. 对含有两个及以上的布尔值张量执行了 or、and、not 这样的操作:
a = torch.tensor([True, False])
b = torch.tensor([False, True])
""" 以下三种操作都会报错 """
print(a or b)
print(a and b)
print(not a)

需要注意的是,如果 a 和 b 都只含一个布尔值,则不会出现错误:

a = torch.tensor([True])
b = torch.tensor([False])
print(a or b)
# tensor([True])
print(a and b)
# tensor([False])
print(not a)
# False
  1. Pytorch 跑模型报错
if labels:
     loss = self.loss_fn(out, labels)
     return out, loss
 else:
     return out

if labels 那一行报错。这一行代码想判断labels是否为空。
因为labels是torch.tensor类型,不能直接转换成bool值。需要改成:

if labels is not None:
   if (labels):

查看类型

print(type(out1)),输出<class 'list'>。list不能直接查看是否相等

使用eq()

import operator
print(operator.eq(out1,out2))

还是报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous

print(out1.eq(out2))

报错AttributeError: 'list' object has no attribute 'eq'

使用list转换成tensor

tensor=torch.tensor(out1)
报错ValueError: only one element tensors can be converted to Python scalars,可能出现的情况:
因为要转换的list里面的元素包含多维的tensor,一般list 转 torch.tensor只需要tensor=torch.tensor(out1),但是要转换的list里面的元素包含多维的tensor,应该使用val= torch.tensor([item.cpu().detach().numpy() for item in out1]).cuda()
这是由于 gpu上的 tensor 不能直接转为 numpy; 须要先在 cpu 上完成操做,再回到 gpu 上。
运行后继续报错ValueError: expected sequence of length 9 at dim 2 (got 2)
说明长度一不一样,一个有9个元素,另一个只有2个。

使用list转换成numpy

ndarray1 = np.array(out1)报错RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
但是out1是list,怎么能用tensor.detach().numpy()呢?

使用debug查询out的具体值

发现out是由多个高维tensor组成的list

编写对比程序

for i in range(len(out)):
    if out1[i]==out2[i]:
       print("true") 

报错RuntimeError: Boolean value of Tensor with more than one value is ambiguous
修改后

for i in range(len(out)):
    if out[i].equal(outs[i]):
       print("true") 

成功!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, I can provide you with a Python implementation of a genetic algorithm to solve your problem. Here's the code: ```python import random import math # Define the fitness function def fitness_func(x): return 0.4 + math.sin(math.pi*4*x)/(math.pi*4*x) + 1.1*math.sin(math.pi*4*x+2)/(math.pi*4*x+2) + 0.8*math.sin(x-2)/(x-2) + 0.7*math.sin(6*x-4)/(6*x-4) # Define the genetic algorithm def genetic_algorithm(population_size, crossover_prob, mutation_prob, iterations): # Initialize the population population = [] for i in range(population_size): individual = ''.join(random.choice(['0', '1']) for _ in range(16)) population.append(individual) # Iterate for a fixed number of times for i in range(iterations): # Evaluate the fitness of each individual fitness = [fitness_func(int(individual, 2)) for individual in population] # Select the best individuals to be parents parents = [] for j in range(int(population_size/2)): parent1 = population[fitness.index(max(fitness))] fitness[fitness.index(max(fitness))] = -1 parent2 = population[fitness.index(max(fitness))] fitness[fitness.index(max(fitness))] = -1 parents.append((parent1, parent2)) # Perform crossover offspring = [] for parent1, parent2 in parents: if random.random() < crossover_prob: crossover_point = random.randint(1, len(parent1)-1) offspring1 = parent1[:crossover_point] + parent2[crossover_point:] offspring2 = parent2[:crossover_point] + parent1[crossover_point:] offspring.append(offspring1) offspring.append(offspring2) else: offspring.append(parent1) offspring.append(parent2) # Perform mutation for j in range(len(offspring)): offspring_individual = list(offspring[j]) for k in range(len(offspring_individual)): if random.random() < mutation_prob: offspring_individual[k] = '0' if offspring_individual[k] == '1' else '1' offspring[j] = ''.join(offspring_individual) # Replace the old population with the new offspring population = offspring # Find the best individual in the final population best_individual = population[0] best_fitness = fitness_func(int(best_individual, 2)) for individual in population: fitness = fitness_func(int(individual, 2)) if fitness > best_fitness: best_individual = individual best_fitness = fitness # Return the best individual and its value return int(best_individual, 2), best_fitness # Call the genetic algorithm with the given parameters x, max_val = genetic_algorithm(30, 0.3, 0.01, 400) print("x = {:.4f}, f(x) = {:.4f}".format(x, max_val)) ``` Explanation: - The `fitness_func` function implements the fitness function of the problem, which is the function `f(x)` given in the question. - The `genetic_algorithm` function implements the genetic algorithm itself. It takes as input the population size, crossover probability, mutation probability, and number of iterations. It returns the best individual and its fitness value. - The algorithm initializes a population of random binary strings of length 16. It then evaluates the fitness of each individual and selects the best individuals to be parents. - The parents are combined using single-point crossover with probability `crossover_prob` to create offspring. The offspring are then mutated with probability `mutation_prob`. - The algorithm iterates for a fixed number of times, replacing the old population with the new offspring in each iteration. - Finally, the algorithm returns the best individual and its fitness value. Note that the genetic algorithm is a stochastic algorithm, so the results may vary each time you run it.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值