【Pytorch学习笔记】从零开始搭建神经网络(2/3)

上一篇介绍了python和pytorch需要懂的逻辑和代码知识

上一篇:python和pytorch需要懂的逻辑和代码知识

这一篇介绍类之间的调用

# !usr/bin/env python3
# -*- coding:utf-8 -*-

"""
@author : 24nemo
 @date  : 2022年03月02日
"""

import numpy as np


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


class Neuron:
    def __init__(self, weight, bias):
        self.weight = weight
        self.bias = bias

    def feedforward(self, input):
        result = np.dot(self.weight, input) + self.bias
        return sigmoid(result)


class OurNeuronNetwork:
    def __init__(self):
        weight = np.array([0, 1])
        bias = 0

        self.h1 = Neuron(weight, bias)
        self.h2 = Neuron(weight, bias)   # 在这只是做了实例化,36行才用到了上面的class的东西
        self.o1 = Neuron(weight, bias)

    def feedforward(self, x):
        out_h1 = self.h1.feedforward(x)
        out_h2 = self.h2.feedforward(x)

        out_o1 = self.o1.feedforward(np.array([out_h1, out_h2]))

        return out_o1


def main():
    # weight = np.array([0, 1])
    # bias = 4
    #
    # input_num = np.array([2, 3])
    # net = Neuron(weight, bias)
    # print(net.feedforward(input_num))
    network = OurNeuronNetwork()  # 把类进行实例化的时候,代码运行时所涉及的只是这个类里面的init中的内容;同样的,在self.h1 = Neuron(weight, bias)这里,调用Neuron这个类时,也是只调用了其中的init方法而已;
    x = np.array([2, 3])
    print(network.feedforward(x))  # 而在这里调用了实例化以后的对象network当中的其他方法,这个时候才去调用对应的方法feedforward;


if __name__ == '__main__':
    main()

明天白天我要把这个程序调试的动图,传上来,这能解决我很久都没有理解的程序内部调用函数和类的问题

备注:多打几个断点,就知道程序是怎么流动的了。在def 和 class这些行,不打断点,其余行都打!

下一步,还要弄清楚,跨模块的程序要如何运行和调用的。
下一篇:调用其他模块的方式

你可能感兴趣的:(Python/Pycharm,深度学习/PyTorch,pytorch,神经网络,深度学习)