Duvidas sobre erro no codigo

estou com problemas para executar os códigos a seguir:

  • CODIGO 1:
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 16:10:10 2020

@author: Unir
"""

import pandas as pd # Biblioteca para leitura de arquivos
from sklearn.neural_network import MLPClassifier # ... RNA

# Ler arquivos CSV
train_data = pd.read_csv("resultados/train_data.csv", header=None,
                         delimiter=",")

test_data = pd.read_csv("resultados/test_data.csv", header=None,
                        delimiter=",")

## Separar em dados de entrada e saída
xTrain = train_data.iloc[::, 0:-1].values
xTest = test_data.iloc[::, 0:-1].values

yTrain = train_data.iloc[::, -1].values
yTest = test_data.iloc[::, -1].values

for k in range(len(yTrain)):
    if yTrain[k] == 0.5:
        yTrain[k] = 0
#
## Função de ativação
activation_ = ["identity", "logistic", "tanh", "relu"]
#
## Método de treinamento
solver_ = ["lbfgs", "sgd", "adam"]
#
## Cria um RNA
clf = MLPClassifier(activation=activation_[2], solver=solver_[0],
                    learning_rate_init=0.01, random_state=1,
                    hidden_layer_sizes=(12, 20, 15, 5), max_iter=50,
                    early_stopping=False)
#
## Treina RNA
clf.fit(xTrain, yTrain)
#
## Verificar precisão
result_island = 0
n_island = 0
result_normal = 0
n_normal = 0
result_sc = 0
n_sc = 0
#
for i in range(0, len(yTest)):
    if yTest[i] == 1:
        n_island += 1
        result_island += (1 if clf.predict(xTest[i].reshape(1,-1))
            else 0)
    elif yTest[i] == 0.5:
        n_sc += 1
        result_sc += (1 if clf.predict(xTest[i].reshape(1,-1)) == 0
                      else 0)
    else:
        n_normal += 1
        result_normal += (1 if clf.predict(xTest[i].reshape(1,-1)) ==
                          yTest[i] else 0)
#
percentage_island = result_island * 100 / n_island
percentage_normal = result_normal * 100 / n_normal
percentage_sc = result_sc * 100 / n_sc
percentage_total = (percentage_island + percentage_normal +
percentage_sc) / 3.0

print("**" * 40)
print("Accuracy for islanding: " + "%.5f" % (percentage_island) + "%")
print("**" * 40)
print("Accuracy for normal: " + "%.5f" % (percentage_normal) + "%")
print("**" * 40)
print("Accuracy for short-circuit: " + "%.5f" % (percentage_sc) + "%")
print("**" * 40)
print("Total accuracy: " + "%.5f" % (percentage_total) + "%")
print("**" * 40)

CODIGO 02:

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 17:23:10 2019

@author: pamel
"""

import numpy as np
import scipy
import scipy.signal
import matplotlib.pyplot as plt



def frft(f, a):
    ret = np.zeros_like(f, dtype=np.complex)
    f = f.copy().astype(np.complex)
    N = len(f)
    shft = np.fmod(np.arange(N) + np.fix(N / 2), N).astype(int)
    dU = np.sqrt(N)
    a = np.remainder(a, 4.0)
    
    #Casos especiais da transformada fracional
    if a == 0.0:
        return f
    if a == 2.0:
        return np.flipud(f)
    if a == 1.0:
        ret[shft] = np.fft.fft(f[shft]) / dU
        return ret
    if a == 3.0:
        ret[shft] = np.fft.ifft(f[shft]) * dU
        return ret

    # Reduz o intervalo de a: 0.5 < a < 1.5
    if a > 2.0:
        a = a - 2.0
        f = np.flipud(f)
    if a > 1.5:
        a = a - 1
        f[shft] = np.fft.fft(f[shft]) / dU
    if a < 0.5:
        a = a + 1
        f[shft] = np.fft.ifft(f[shft]) * dU

    # para todo a pertenente a 0.5 < a < 1.5
    alpha = a * np.pi / 2
    tana2 = np.tan(alpha / 2)
    sina = np.sin(alpha)
    f = np.hstack((np.zeros(N - 1), sincinterp(f), np.zeros(N - 1))).T

    # chirp premultiplication
    chrp = np.exp(-1j * np.pi / N * tana2 / 4 *
                     np.arange(-2 * N + 2, 2 * N - 1).T ** 2)
    f = chrp * f

    # chirp convolution
    c = np.pi / N / sina / 4
    ret = scipy.signal.fftconvolve(
        np.exp(1j * c * np.arange(-(4 * N - 4), 4 * N - 3).T ** 2),
        f
    )
    ret = ret[4 * N - 4:8 * N - 7] * np.sqrt(c / np.pi)

    # chirp post multiplication
    ret = chrp * ret

    # normalizing constant
    ret = np.exp(-1j * (1 - a) * np.pi / 4) * ret[N - 1:-N + 1:2]

    return ret

#Calcula a inversa fracional de Fourier
def ifrft(f, a):
   return frft(f, -a)


def sincinterp(x):
    N = len(x)
    y = np.zeros(2 * N - 1, dtype=x.dtype)
    y[:2 * N:2] = x
    xint = scipy.signal.fftconvolve(
        y[:2 * N],
        np.sinc(np.arange(-(2 * N - 3), (2 * N - 2)).T / 2),
    )
    return xint[2 * N - 3: -2 * N + 3]

if __name__ == "__main__":
    print('FrFT')

CODIGO 03:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 30 17:03:35 2019

@author: Leonardo Audalio
     
"""

import os
import pandas as pd
import numpy as np
import pywt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from multiprocessing import Pool, Lock
from frft import *

def energy(array_):
    return np.sum(array_**2)


def putinorder(files, order):
    temp = [""] * len(order)
    for i in range(len(order)):
        for file in files:
            if order[i] in file:
                temp[i] = file
                break
    return temp
    

def repeat(list_, arg_a, arg_b):
    N = len(list_)
    temp = []
    for k in range(N):
        temp += [[list_[k], arg_a, arg_b]]
    return temp


def process(args_):
    temp = []
    path_ = args_[0]
    inicio_ = args_[1]
    fim_ = args_[2]
    files = putinorder(os.listdir(path_), ["Va", "Vb", "Vc", "Ia", "Ib", "Ic", "f"]) # "Ia", "Ib", "Ic","Va", "Vb", "Vc","f"
    global case
    
    lock.acquire()
    case += 1
    print("Case:", case)
    lock.release()
    for filename in files:
        # Read file
        ca = pd.read_csv(path_ + filename, header=None, delimiter=',').iloc[:].values.transpose()[0]
        ca = ca[int(len(ca)*inicio_/40):int(len(ca)*fim_/40):4]# esotu usando 6
        ca = frft(ca, 0.5)
        ca = np.abs(ca)
        temp.append(energy(ca))
        temp.append(np.std(ca, ddof=1))
   
    if "island" in filename:
        temp.append(2)
    elif "sc" in filename:
        temp.append(1)
    else:
        temp.append(0)
    return temp


if __name__ == "__main__":
    directories = [dir_ for dir_ in os.listdir("dados") if os.path.isdir("dados")]
    case = 0
    
    
    intervalos =[[1.5, 2.5], [2.5, 3.5], [3.5, 4.5], [6, 7], [10,11],[14,15],[16,17], 
                 [20,21],[22,23],[23,24],[24,25],[25,26]]
    results = []
       
    lock = Lock()
   
    for dir_ in directories:
        for intervalo in intervalos:
            path_relative = "dados/" + dir_ + "/"
            sub_dir = [path_relative + x + "/" for x in os.listdir(path_relative)]
            pool = Pool(processes=1)
            
            result = pool.map(process, repeat(sub_dir, intervalo[0], intervalo[1]))
            results += result
            
    
#    if results != []:
#        # Splitting training and testing data in 60% and 40%, respectively
#        train_data, test_data = train_test_split(results, test_size=0.4, random_state=0)
#    
#        # Normalizing input data between 0 and 1
#        scaler = MinMaxScaler()
#        train_data = scaler.fit_transform(train_data)
#        test_data = scaler.transform(test_data)
#    
#        # Writing csv files for training and testing data
#        np.savetxt(fname="resultados/train_data.csv", X=train_data, fmt="%.15f", delimiter=",")
#        np.savetxt(fname="resultados/test_data.csv" , X=test_data, fmt="%.15f", delimiter=",")

erro:

C:\Users\nezin\AppData\Local\Programs\Python\Python39\python.exe C:\Users\nezin\Downloads\rna-1.py 
Traceback (most recent call last):
  File "C:\Users\nezin\Downloads\rna-1.py", line 12, in <module>
    train_data = pd.read_csv("resultados/train_data.csv", header=None,
  File "C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\parsers\readers.py", line 948, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\parsers\readers.py", line 611, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\parsers\readers.py", line 1448, in __init__
    self._engine = self._make_engine(f, self.engine)
  File "C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\parsers\readers.py", line 1705, in _make_engine
    self.handles = get_handle(
  File "C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\common.py", line 863, in get_handle
    handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'resultados/train_data.csv'

Process finished with exit code 1

grato pela ajuda

Você pegou esse código em algum lugar e quer que ele funcione? É isso? Nessa pasta C:\Users\nezin\Downloads\resultados\ está faltando o arquivo train_data.csv. Leia o erro, não é tão difícil identificar isso, a não ser que você não tenha ideia do que está fazendo. O erro foi originado na linha 12 do arquivo rna-1.py:

File “C:\Users\nezin\Downloads\rna-1.py”, line 12, in
train_data = pd.read_csv(“resultados/train_data.csv”, header=None,

E o que realmente gerou o erro foi não encontrar o arquivo:

File “C:\Users\nezin\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\common.py”, line 863, in get_handle
handle = open(
FileNotFoundError: [Errno 2] No such file or directory: ‘resultados/train_data.csv’

1 curtida

Olá, essa é a parte do código que está gerando o erro, a reposta que recebe é que ele não encontrou o arquivo de treino.
verifique se possui os arquivos csv necessários.