我在这里所做的事情没有在这个类中返回输出?

问题描述 投票:0回答:2

我的朋友为我们在 main 中使用的代码创建了一个类,我们正在尝试调试它。我有限的经验和缺乏沟通让我感到困惑。这是代码:

任何需要的东西都在其他地方定义,并且所有需要的库都被导入

class NN:
    def __init__(self, data_path, n_hidden,epochs):
        # loading data set
        self.data_path = data_path
        self.data = pd.read_csv(data_path, nrows=1000).values
        self.xtr = self.data[:, 1:]
        self.ytr = self.data[:, 0]
        self.epochs = epochs

        # define network hyperparameters
        self.n_hidden = n_hidden
        self.n_input = self.xtr.shape[1]
        self.n_samples = self.xtr.shape[0]
        self.n_out = len(np.unique(self.ytr))
        self.accuracy = []
        self.accum_accuracy = 0
        self.alpha = 0.01
        self.yhat_max = 0

        # create weights of the network
        self.whi = np.random.uniform(-1, 1, size=(self.n_hidden,self.n_input))
        self.who = np.random.uniform(-1, 1, size=(self.n_out,self.n_hidden))

        # One-hot encoding
        self.ytr_hot = np.zeros((self.xtr.shape[0], self.n_samples))
        self.ytr_hot[np.arange(0, len(self.ytr)), self.ytr] = 1

    # data forward pass
    def forward_pass(self):
        for epoch in range(self.epochs):
            self.accum_accuracy = 0
            for i in range(self.n_samples):
                # hidden layer
                self.h_logit = np.dot(self.xtr[i, :], self.whi.T)
                self.hidden_out = sigmoid(self.h_logit)

                # output layer
                self.o_logit = np.dot(self.hidden_out,self.who.T)
                self.yhat = sigmoid(self.o_logit)

                # Append the max indices of the output layer and compute accumulated accuracy
                self.yhat_max = np.argmax(self.yhat)
                self.accum_accuracy += self.yhat_max == self.ytr[i]

                # Estimate the network error
                self.error = self.yhat - self.ytr_hot[i, :]
                self.who -= self.alpha * np.outer(self.error, self.hidden_out)

            self.accuracy.append(100*self.accum_accuracy/self.n_samples)
        return self.accuracy

在没有明确方向的情况下谷歌搜索并弄乱代码。我期待输出的准确性。

发生的事情没什么。我将运行或调试代码,当我期望输出准确性时,不会显示任何内容

python class machine-learning deep-learning neural-network
2个回答
0
投票

简单返回准确度:

return self.accuracy

目前,您正在返回其

append
方法。


0
投票

问题在于代码定义了 NN 类及其方法,但没有创建该类的实例或调用其forward_pass 方法来获取输出。您应该实例化 NN 类并调用其forward_pass 方法来查看准确度输出。

像这样:

data_path = "path/to/your/data.csv"
n_hidden = 10
epochs = 5

nn_model = NN(data_path, n_hidden, epochs)

accuracy = nn_model.forward_pass()
print(accuracy)
© www.soinside.com 2019 - 2024. All rights reserved.