如何正确使用数字0在python中

2024-09-26 22:54:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习机器学习,我在github中找到了这段代码,但是我在使它正确工作方面遇到了一些问题,而且我也没有使用python的经验,这并不能使事情变得更简单,哈哈哈

filhos = np.zeros( (n_filhos, n_vars) ) is returning this error:

Traceback (most recent call last): File "D:\GitHub\evoman_framework\optimization_individualevolution_demo.py", line 272, in filhos = cruzamento(pop) # crossover File "D:\GitHub\evoman_framework\optimization_individualevolution_demo.py", line 171, in cruzamento filhos = np.zeros( (n_filhos, n_vars) ) TypeError: only integer scalar arrays can be converted to a scalar index

############################################################################### 
# EvoMan FrameWork - V1.0 2016                                    #
# DEMO : Neuroevolution - Genetic Algorithm with perceptron neural network.   #
# Author: Karine Miras                                                #
# karine.smiras@gmail.com                                         #
############################################################################### 

# imports framework
import sys
sys.path.insert(0, 'evoman') 
from environment import Environment
from controller import Controller

# imports other libs 
import time
import numpy as np
from math import fabs,sqrt
import glob, os

# genetic algorithm params

run_mode = 'train' # train or test
stateread = None # 'state_1' 
statesave = 'state_1'
n_vars = (env.get_num_sensors()+1)*5  # perceptron
#n_vars = (env.get_num_sensors()+1)*10 + 11*5  # multilayer with 10 neurons
#n_vars = (env.get_num_sensors()+1)*50 + 51*5 # multilayer with 50 neurons
dom_u = 1
dom_l = -1
npop = 100
gens = 30
mutacao = 0.2
last_best = 0

# crossover
def cruzamento(pop):

    total_filhos = np.zeros((0,n_vars))


    for p in range(0,pop.shape[0], 2):       
        p1 = torneio(pop)
        p2 = torneio(pop)

        n_filhos =   np.random.randint(1,3+1, 1) 
        filhos =  np.zeros( (n_filhos, n_vars) )

        for f in range(0,n_filhos): 

            cross_prop = np.random.uniform(0,1)
            filhos[f] = p1*cross_prop+p2*(1-cross_prop)

            # mutation 
            for i in filhos[f]:
                if np.random.uniform(0 ,1)<=mutacao:
                    filhos[f][i] =   filhos[f][i]+np.random.normal(dom_l, dom_u)

            filhos[f] = np.array(map(lambda y: limites(y), filhos[f]))           

            total_filhos = np.vstack((total_filhos, filhos[f]))

    return total_filhos

Tags: infromimportwithnpzerosframeworkrandom
2条回答

出现此错误是因为您的n_filhosn_vars类型不是整数。我只能单独运行第一个变量,它返回数组。在

>>> n_filhos = np.random.randint(1,3+1, 1) 
>>> n_filhos
array([3])

在运行前,先检查一下它们的类型。在

np.random.randint(1,3+1, 1)返回数组,而不是整数。维度规范需要整数元组。相反,有一个numpy数组的元组和一个整数:

>>> np.random.randint(1,3+1, 1)
array([2])

相关问题 更多 >

    热门问题