Pyomo: KeyError: "Index '(0, 1, 1)' is not valid for indexed component 'x_ijl'" - python
With reference to the images in the attached files, i want to model using pyomo.
What I have done so far.
from pyomo.environ import *
from pyomo.opt import SolverFactory
import pyomo.environ
n=13
distanceMatrix=[[0,8,4,10,12,9,15,8,11,5,9,4,10],
[8,0,7,6,8,6,7,10,12,9,8,7,5],
[4,7,0,7,9,5,8,5,4,8,6 ,10,8],
[10,6 ,7,0,6,11,5 ,9,8,12,11,6,9],
[12,8 ,9,6, 0,7,9,6,9,8,4,11,10],
[9,6,5,11,7,0,10,4,3,10,6,5,7],
[15,7 ,8,5,9,10,0,10,9,8,5,9,10],
[8,10 ,5,9,6,4,10,0,11,5,9,6,7],
[11,12,4,8, 9,3,9,11,0, 9,11,11,6],
[5,9,8,12,8,10,8,5,9,0,6,7,5],
[9,8,6,11,4,6,5,9,11,6,0,10,7],
[4,7,10,6,11,5,9,6,11,7,10,0,9],
[10,5,8,9,10,7,10,7,6,5,7,9,0]]
travel_time=[[0,8,4,10,12,9,15,8,11,5,9,4,10],
[8,0,7,6,8,6,7,10,12,9,8,7,5],
[4,7,0,7,9,5,8,5,4,8,6 ,10,8],
[10,6 ,7,0,6,11,5 ,9,8,12,11,6,9],
[12,8 ,9,6, 0,7,9,6,9,8,4,11,10],
[9,6,5,11,7,0,10,4,3,10,6,5,7],
[15,7 ,8,5,9,10,0,10,9,8,5,9,10],
[8,10 ,5,9,6,4,10,0,11,5,9,6,7],
[11,12,4,8, 9,3,9,11,0, 9,11,11,6],
[5,9,8,12,8,10,8,5,9,0,6,7,5],
[9,8,6,11,4,6,5,9,11,6,0,10,7],
[4,7,10,6,11,5,9,6,11,7,10,0,9],
[10,5,8,9,10,7,10,7,6,5,7,9,0]]
Time_windows = [(1400,1500), (0000,2400), (0000,2400),(0700,2400),(0000,2400),(0000,0700),(0700,2400),(0700,2400),(0000,0700),(0000,2400),\
(0000,2400),(0000,2400),(0700,2400)]
Service_time = [0000, 1600,1600,180,30,120,120,60,30,30,90,120,330]
demand = [9999.00, 9999.00,9999.00,12.00, 4.00, 6.00, 8.00,16.00,6.00,16.00,12.00,24.00,8.00]
K = 4 # no. of vehicles
C = 280; # capacity
speed = 40; # default speed
M = 200;
startCity = 0
model = ConcreteModel()
# sets
#model.M = Set(initialize=range(1, n+1))
model.N = Set(initialize=range(1, n+1))
model.K = Set(initialize=range(1, K+1))
model.Nc = Set(initialize=range(3, n+1)) # set of customers
# Param
model.cost = Param(model.N, model.N, initialize=lambda model, i, j: distanceMatrix[i-1][j-1])
model.travel_time = Param(model.N, model.N,initialize=lambda model, i,j: travel_time[i-1][j-1])
model.Time_windows = Param(model.N, initialize=lambda model, i: travel_time[i-1]) # time_windows
model.Service_time = Param(model.N, initialize=lambda model, i: Service_time[i-1]) # Service time
model.demand = Param(model.N, initialize=lambda model, i: demand[i-1])
model.M = Param(initialize=M)
model.C = Param(initialize=C)
# variables
model.x_ijl = Var(model.N, model.N, model.K, within=Binary) # decision variable = 1 iff vehicle l in K uses arc (i,j) in A
model.d_il = Var(model.N, model.K, bounds=(0,None)) # the accumulative demand at node i in V for vehicle l in K
model.w_il = Var(model.N, model.K, bounds=(0,None)) # start time of service at node i in V for vehicle l in K
"""
Constriants
"""
# All l vehicles must leave the depot
def leave_depot(model,l):
return sum(model.x_ijl[0,j,l] for j in model.N) == 1
model.leave_depot = Constraint(model.K, rule=leave_depot)
# All l vehicles must return to the depot
def return_depot(model,l):
return sum(model.x_ijl[i,0,l] for i in model.N) == 1
model.return_depot = Constraint(model.K, rule=return_depot)
# ensures that all customers are serviced exactly once.
def customer_service(model, j):
return sum(sum(model.x_ijl[i,j,l] for l in model.K) for i in model.N) ==1
model.customer_service1 = Constraint(model.Nc, rule=customer_service)
# Inflow and outflow must be equal except for the depot nodes
def flow(model,j,l):
return sum(model.x_ijl[i,j,l] for i in model.N if i < j) == sum(model.x_ijl[j,i,l] for i in model.N if j < i)
model.flow1 = Constraint(model.N,model.K, rule=flow)
# Time windows
def time_windows1(model,i,l):
return model.Time_windows[i][0] <=model.w_il[i,l] <= model.Time_windows[i][1]
model.time_windows = Constraint(model.N,model.K, rule=time_windows1)
# service time
def service_time(model,i,j,l):
return model.w_il[i,l] + model.Service_time[i] + model.travel_time[i,j] <= model.w_il[j,l] + (1 - model.x_ijl[i,j,l])*200
model.service_time = Constraint(model.N, model.N, model.K, rule=service_time)
# vehicle must be empty at start and end of routes
def empty(model, l):
return model.d_il[0,l] + model.d_il[-1,l] == 0
model.empty = Constraint(model.K, rule=empty)
# accumulative demand for all nodes except disposal sites
def demands_forall_nodes(model,i,j,l):
return model.d_il[i,l] + model.demand[i] <= model.d_il[j,l]+(1 - model.x_ijl[i,j,l]*200)
model.demands_forall_nodes = Constraint(model.Nc, model.N,model.K,rule=demands_forall_nodes)
# Capacity contraints
def vehicle_capacity(model, i,l):
return model.d_il[i,l] <= model.C
model.vehicle_capacity = Constraint(model.N, model.K, rule=vehicle_capacity)
# Objective Function
def objective(model):
return sum(model.cost[i,j]*model.x_ijl[i,j,l] for i in model.N for j in model.N for l in model.K)
model.obj = Objective(rule=objective)
opt = SolverFactory("glpk")
results = opt.solve(model, tee=True)
results.write()
However, I got an error with constriant 2 (from image 2) which I know similar will apply to constraint 3 and constriant 9. The error is:
ERROR: Rule failed when generating expression for constraint leave_depot with
index 1: KeyError: "Index '(0, 1, 1)' is not valid for indexed component
'x_ijl'"
ERROR: Constructing component 'leave_depot' from data=None failed: KeyError:
"Index '(0, 1, 1)' is not valid for indexed component 'x_ijl'"
Traceback (most recent call last):
File "vrptwModel.py", line 81, in <module>
model.leave_depot = Constraint(model.K, rule=leave_depot)
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/block.py", line 540, in __setattr__
self.add_component(name, val)
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/block.py", line 980, in add_component
val.construct(data)
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/constraint.py", line 793, in construct
ndx)
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/misc.py", line 61, in apply_indexed_rule
return rule(model, index)
File "vrptwModel.py", line 80, in leave_depot
return sum(model.x_ijl[0,j,l] for j in model.N) == 1
File "vrptwModel.py", line 80, in <genexpr>
return sum(model.x_ijl[0,j,l] for j in model.N) == 1
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/indexed_component.py", line 543, in __getitem__
index = self._validate_index(index)
File "/usr/local/lib/python2.7/dist-packages/pyomo/core/base/indexed_component.py", line 695, in _validate_index
% ( idx, self.name, ))
KeyError: "Index '(0, 1, 1)' is not valid for indexed component 'x_ijl'"
My problem is modeling constraint 2 and 3.
Please could someone help me to write these constraints correctly
The problem is that you started your indexing sets at 1 not 0. Change m.x_ijl[0,j,l] to m.x_ijl[1,j,l].
Related
KeyError in a recursive function in python
I am defining a main_meal_model function to list a lunch plan that takes in a day value. I have previously defined a random_main_meal_dataset function that creates a database of all the foods that are to be eaten at lunch which also takes in the same day value. For some reason i can't omit a forced declaration of the day value in the random_main_meal_dataset function, else it either gives a KeyError or NameError I have tried every day of the week and it seems perfect as much as my forced declaration is the same as the day value i send when calling the main_meal_model function but as soon as i try to make this an automatic correspondance it sends KeyError: 'Monday' or NameError: name 'day' is not defined per day_data = data[day] Error messages: Full Errorr messages: Traceback (most recent call last): File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 104, in <module> print(main_meal_model('Monday', 70, 2000, data, 'Lunch')) File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 72, in main_meal_model day_data = data[day] KeyError: 'Monday or Traceback (most recent call last): File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 103, in <module> print(main_meal_model('Monday', 70, 2000, data, 'Lunch')) File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 71, in main_meal_model day_data = data[day] NameError: name 'day' is not defined Here is the part of the code I suppose is causing the problem https://pastebin.com/w8XQ8rTn split_values_day = np.linspace(0, len(data), 8).astype(int) split_values_day[-1] = split_values_day[-1]-1 def random_main_meal_dataset(data, day): data = data[data['meal'].str.contains('Main Dishes|Condiments|Side Dishes', na=False)] frac_data = data.sample(frac=1).reset_index().drop('index', axis=1) day_data = [] for s in range(len(split_values_day)-1): day_data.append( frac_data.loc[split_values_day[s]:split_values_day[s+1]]) return dict(zip(day, day_data)) # define a lunch / dinner model that takes in prob, kg, calories, data and makes a lunch / dinner plan for the day def main_meal_model(day, kg, calories, data, meal): data = random_main_meal_dataset(data, day=['Monday']) G = extract_gram(build_nutritional_values(kg, calories)) E = G['Carbohydrates Grams'] F = G['Fat Grams'] P = G['Protein Grams'] day_data = data[day] day_data = day_data[day_data.calories != 0] food = day_data.name.tolist() c = day_data.calories.tolist() x = pulp.LpVariable.dicts( "x", indices=food, lowBound=0, upBound=1.5, cat='Continuous', indexStart=[]) e = day_data.carbohydrate.tolist() f = day_data.total_fat.tolist() p = day_data.protein.tolist() div_meal = meal_split[meal] prob = pulp.LpProblem("Diet", LpMinimize) prob += pulp.lpSum([x[food[i]]*c[i] for i in range(len(food))]) prob += pulp.lpSum([x[food[i]]*e[i] for i in range(len(x))]) >= E*0.35 prob += pulp.lpSum([x[food[i]]*f[i] for i in range(len(x))]) >= F*0.35 prob += pulp.lpSum([x[food[i]]*p[i] for i in range(len(x))]) >= P*0.35 prob.solve(PULP_CBC_CMD(msg=0)) variables = [] values = [] for v in prob.variables(): variable = v.name value = v.varValue variables.append(variable) values.append(value) values = np.array(values).round(2).astype(float) sol = pd.DataFrame(np.array([food, values]).T, columns=['Food', 'Quantity']) sol['Quantity'] = sol.Quantity.astype(float) sol = sol[sol['Quantity'] != 0.0] sol.Quantity = sol.Quantity*100 sol = sol.rename(columns={'Quantity': 'Quantity (g)'}) return sol print(main_meal_model('Monday', 70, 2000, data, 'Lunch'))`
problem with moving data from device to host
Hi I'm trying to create an AI inspired NEAT but I ran into a problem after performing the calculation, the data from the device can't be moved to the host. I'm trying to use cuda.synchronize () before moving the data, but in this case the error has already occurred on this line. I tried the cuda features before and they worked without problems until now. I'm attaching the code with an error. Please can you help me? code: import os # needs to appear before cuda import os.environ["NUMBA_ENABLE_CUDASIM"] = "0" # set to "1" for more debugging, but slower performance os.environ["NUMBA_CUDA_DEBUGINFO"] = "0" from numba import cuda import numpy as np from random import uniform from pprint import pprint #cuda.jit(device=True) def LeakyRelu(x): return max(x * 0.1, x) #cuda.jit def Calculate(set_io, many_neurons, many_inputs, reindex_io, memory_io, weights_io, biases_io, nets_info_io, auxmemort_io): x = cuda.grid(1) shape = set_io.shape if x < shape[0]: netidx = reindex_io[x, 0] neuidx = reindex_io[x, 1] weiidx = reindex_io[x, 2] result = 0 for i in range(nets_info_io[netidx, 1]): result += memory_io[nets_info_io[netidx, 0] + i] * weights_io[weiidx + i] result += biases_io[x] result = LeakyRelu(result) auxmemort_io[neuidx] = result def CalculateSlow(): pass class ANET: def __init__(self, many_inputs, many_outputs, many_networks, info = True, activation_function = LeakyRelu): self.many_inputs = many_inputs self.many_outputs = many_outputs self.many_networks = many_networks self.activation_function = activation_function self.info = info self.netid = -1 self.cuda_many_input = cuda.to_device(self.many_inputs) if self.info: print("starting Setup:\n|") device = str(cuda.get_current_device()).split("'b'")[1].split("''")[0] print(f"| cuda run on: {device}") print(f"| generate genomes") self.networks_genomes = [self._GenerateGenome() for _ in range(self.many_networks)] self._BuildPopulation() def _CudaPre(self, block, array): griddim = tuple(np.array(array.shape) // block + 1) blockdim = tuple(np.full_like(griddim, block)) return griddim, blockdim def _GenerateGenome(self): neurons_genome = [[self.activation_function, uniform(-1,1), i + self.many_inputs] for i in range(self.many_outputs)] synapses_genome = [[[i, ii], uniform(-1,1), True] for i in range(self.many_inputs) for ii in range(self.many_inputs, self.many_outputs + self.many_inputs)] self.netid += 1 return [neurons_genome, synapses_genome, self.netid] def _BuildPopulation(self): memory_len = sum([(len(i[0]) + self.many_inputs) for i in self.networks_genomes]) memory = np.zeros(memory_len, dtype=np.float64) auxmemory = np.copy(memory) weights_len = sum([(len(i[1]) + self.many_inputs + 1) for i in self.networks_genomes]) weights = np.zeros(weights_len, dtype=np.float64) biases_len = sum([len(i[0]) for i in self.networks_genomes]) biases = np.zeros(biases_len, dtype=np.float64) nets_info = np.zeros([self.many_networks, 5], dtype=np.int64) movmem = 0 movwei = 0 movbia = 0 for idx,i in enumerate(self.networks_genomes): nets_info[idx] = (movmem, len(i[0]) + self.many_inputs, movwei, movbia, i[2]) movmem += len(i[0]) + self.many_inputs movwei += len(i[1]) + self.many_inputs + 1 movbia += len(i[0]) biaidx = 0 for genome, net_info in zip(self.networks_genomes, nets_info): for gen, biagen in zip(genome[1], genome[0]): if gen[2]: if gen[0][0] < self.many_inputs: target = gen[0][0] else: target = genome[0][gen[0][0] - self.many_inputs - self.many_outputs][2] + self.many_inputs weights[(gen[0][1] - self.many_inputs) * net_info[1] + net_info[2] + target] = gen[1] biases[biaidx] = biagen[1] biaidx += 1 reindex = np.empty([sum([(i[1] - self.many_inputs) for i in nets_info]), 3], dtype=np.int64) write = 0 weiidx = 0 for idx,inf in enumerate(nets_info): for i in range(inf[1] - self.many_inputs): reindex[write][0] = idx reindex[write][1] = inf[0] + i + self.many_inputs reindex[write][2] = weiidx weiidx += inf[1] write += 1 if self.info: print("| move arrays to device") self.memory = memory self.cuda_auxmemory = cuda.to_device(auxmemory) print(self.cuda_auxmemory.copy_to_host()) self.cuda_weights = cuda.to_device(weights) self.cuda_biases = cuda.to_device(biases) self.nets_info = nets_info self.cuda_nets_info = cuda.to_device(nets_info) self.many_neurons = np.sum(nets_info, axis=0)[1] self.cuda_many_neurons = cuda.to_device(self.many_neurons) self.cuda_reindex = cuda.to_device(reindex) # print(nets_info) # print(f"{memory_len} | {weights_len} | {biases_len}") def MathPopulation(self, inputs): for idx, inp in enumerate(inputs): self.memory[self.nets_info[idx][0]: self.nets_info[idx][0] + self.many_inputs] = inp self.cuda_memory = cuda.to_device(self.memory) setlen = cuda.to_device(np.zeros(self.many_neurons)) Calculate[self._CudaPre(32, np.empty([self.many_neurons]))](setlen, self.cuda_many_neurons, self.cuda_many_input, self.cuda_reindex, self.cuda_memory, self.cuda_weights, self.cuda_biases, self.cuda_nets_info, self.cuda_auxmemory) # cuda.synchronize() arr = self.cuda_auxmemory.copy_to_host() print(arr) if __name__ == '__main__': anet = ANET(many_inputs = 3, many_outputs = 2, many_networks = 5) # pprint(anet._GenerateGenome()) anet.MathPopulation([[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]) error: Traceback (most recent call last): File "c:\Users\Ondra\Documents\Pythonporno\ANET\ANET.py", line 144, in <module> anet.MathPopulation([[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]) File "c:\Users\Ondra\Documents\Pythonporno\ANET\ANET.py", line 138, in MathPopulation arr = self.cuda_auxmemory.copy_to_host() File "C:\Users\Ondra\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\cuda\cudadrv\devices.py", line 232, in _require_cuda_context return fn(*args, **kws) File "C:\Users\Ondra\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\cuda\cudadrv\devicearray.py", line 277, in copy_to_host _driver.device_to_host(hostary, self, self.alloc_size, File "C:\Users\Ondra\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\cuda\cudadrv\driver.py", line 2998, in device_to_host fn(host_pointer(dst), device_pointer(src), size, *varargs) File "C:\Users\Ondra\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\cuda\cudadrv\driver.py", line 319, in safe_cuda_api_call self._check_ctypes_error(fname, retcode) File "C:\Users\Ondra\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\cuda\cudadrv\driver.py", line 384, in _check_ctypes_error raise CudaAPIError(retcode, msg) numba.cuda.cudadrv.driver.CudaAPIError: [700] Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR
Python ValueError: setting an array element with a sequence.I'm getting this value error and I don't know how to solve the issue
def simulate(self, timesteps, **kwargs): pos = {comp: i for i, comp in enumerate(kwargs)} population = np.zeros(len(pos), dtype='int') for comp in pos: population[pos[comp]] = kwargs[comp] # line where the error is values = [] values.append(population) comps = list(self.transitions.nodes) time = np.arange(1, timesteps, 1, dtype='int') for t in time: pop = values[-1] new_pop = values[-1].copy() N = np.sum(pop) I am having this value error and I'm not sure on how to fix it. Any suggestion Error happens when I call this, if population is None: population = SIR1.values_.iloc[-1].copy() else: population = pd.concat([population, SIR1.values_.iloc[-1]]) S0 = population.S I00 = population.I R0 = population.R Quarantine.simulate(365 - 74, S=S0, I=I00, R=R0) ### Line causing the error
When I tried to use pyomoNLP on Window, it gave some error
# __________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of Sandia, LLC, the U.S. Government retains certain # rights in this software. # This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ from pyomo.contrib.pynumero.sparse import BlockSymMatrix from pyomo.contrib.pynumero.interfaces import PyomoNLP import matplotlib.pylab as plt import pyomo.environ as aml import pyomo.dae as dae def create_problem(begin, end): m = aml.ConcreteModel() m.t = dae.ContinuousSet(bounds=(begin, end)) m.x = aml.Var([1, 2], m.t, initialize=1.0) m.u = aml.Var(m.t, bounds=(None, 0.8), initialize=0) m.xdot = dae.DerivativeVar(m.x) def _x1dot(M, i): if i == M.t.first(): return aml.Constraint.Skip return M.xdot[1, i] == (1-M.x[2, i] ** 2) * M.x[1, i] - M.x[2, i] + M.u[i] m.x1dotcon = aml.Constraint(m.t, rule=_x1dot) def _x2dot(M, i): if i == M.t.first(): return aml.Constraint.Skip return M.xdot[2, i] == M.x[1, i] m.x2dotcon = aml.Constraint(m.t, rule=_x2dot) def _init(M): t0 = M.t.first() yield M.x[1, t0] == 0 yield M.x[2, t0] == 1 yield aml.ConstraintList.End m.init_conditions = aml.ConstraintList(rule=_init) def _int_rule(M, i): return M.x[1, i] ** 2 + M.x[2, i] ** 2 + M.u[i] ** 2 m.integral = dae.Integral(m.t, wrt=m.t, rule=_int_rule) m.obj = aml.Objective(expr=m.integral) m.init_condition_names = ['init_conditions'] return m instance = create_problem(0.0, 10.0) # Discretize model using Orthogonal Collocation discretizer = aml.TransformationFactory('dae.collocation') discretizer.apply_to(instance, nfe=100, ncp=3, scheme='LAGRANGE-RADAU') discretizer.reduce_collocation_points(instance, var=instance.u, ncp=1, contset=instance.t) # Interface pyomo model with nlp nlp = PyomoNLP(instance) x = nlp.create_vector_x() lam = nlp.create_vector_y() # Evaluate jacobian jac_c = nlp.jacobian_g(x) plt.spy(jac_c) plt.title('Jacobian of the constraints\n') plt.show() # Evaluate hessian of the lagrangian hess_lag = nlp.hessian_lag(x, lam) plt.spy(hess_lag) plt.title('Hessian of the Lagrangian function\n') plt.show() # Build KKT matrix kkt = BlockSymMatrix(2) kkt[0, 0] = hess_lag kkt[1, 0] = jac_c plt.spy(kkt.tocoo()) plt.title('KKT system\n') plt.show() Error: Traceback (most recent call last): File "C:/Users/user/Google Drive/k_aug_M/test/CSTR_ex_declare/check_para_k_aug(KKT)/check.py", line 66, in <module> nlp = PyomoNLP(instance) File "C:\Users\user\.conda\envs\env_name\lib\site-packages\pyomo\contrib\pynumero\interfaces\nlp.py", line 1484, in __init__ super(PyomoNLP, self).__init__(nl_file) File "C:\Users\user\.conda\envs\env_name\lib\site-packages\pyomo\contrib\pynumero\interfaces\nlp.py", line 858, in __init__ self._asl = _asl.AmplInterface(self._model) File "C:\Users\user\.conda\envs\env_name\lib\site-packages\pyomo\contrib\pynumero\extensions\asl.py", line 34, in __init__ % (os.name,) ) RuntimeError: ASL interface is not supported on this platform (nt) Exception AttributeError: "'AmplInterface' object has no attribute 'ASLib'" in <bound method AmplInterface.__del__ of <pyomo.contrib.pynumero.extensions.asl.AmplInterface object at 0x000000000E48BA88>> ignored How can I use pyomoNLP on window?
pandas: AttributeError: 'dict' object has no attribute 'transform'
I'm quite new with python and pandas, and I'm stuck with an error. I'm working with audiofiles, and I need to extract some features from audiostreams. def load_features(self, audio_file): def stereo_to_mono(x): # stereo to mono if len(x.shape) > 1 and x.shape[1] > 1: print('Converting stereo to mono') x = x.mean(axis=1) return x def cut_or_pad_to_length(x, duration, fs): desired_length = int(round(duration * fs)) length = len(x) diff = length - desired_length abs_diff = abs(diff) if diff < 0: print('Padding') # put the short signal in the middle pad_before = abs_diff // 2 pad_after = abs_diff - pad_before x = np.lib.pad(x, (pad_before, pad_after), 'constant') elif diff > 1: print('Cutting') # cut the beginning x = x[0:desired_length] return x def adjust_input(x, fs): x = stereo_to_mono(x) x = cut_or_pad_to_length(x, 2.0, fs) return x #x is data, fs is samplerate x, fs = sf.read(audio_file) x0 = adjust_input(x, fs) # pitchgram x_features = self.ch.transform(x0) if self.scaler is not None: x_features = self.scaler.transform(x_features.reshape(1, -1)) \ # 1 data point with 2D features x_features = x_features.reshape(1, *x_features.shape) return x_features def predict_class_label(self, audio_file): x_features = self.load_features(audio_file) instrument_class = np_utils.probas_to_classes(self.model.predict(x_features, verbose=0))[0] label = self.instr_family_le.inverse_transform(instrument_class) return label This gives me following error: File "C:/dipl0m/ml-master/instrument-classification/predict.py", line 104, in predict_probabilities x_features = self.load_features(audio_file) File "C:/dipl0m/ml-master/instrument-classification/predict.py", line 87, in load_features x_features = self.ch.transform(x0) AttributeError: 'dict' object has no attribute 'transform' But x and x0 don't seems like dictionary, because I operate with them like lists, but transform gives me that error ... Or am I wrong somewhere? Can't figure it out for a long time.