单隐层前馈神经网络tensorflow实现

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

# -*- coding: utf-8 -*-
import tensorflow as tf

# 模拟一个 M-P 神经元
class neuron(object):
    def __init__(self, weight, threshold):
        self.weight = weight  # weight为本神经元的权重,tf.constant
        self.threshold = threshold  # threshold 是这个神经元的阈值,tf.constant

    # 计算函数
    def computes(self, input_value):  # input_value 是输入值, 类型为一维的tf.constant
        sess = tf.Session()
        ans = sess.run(
            tf.nn.relu(tf.to_float(sess.run(tf.reduce_sum(tf.multiply(input_value, self.weight)) - self.threshold))))
        sess.close()
        return ans

# 模拟神经网络中的一层
class Dense(object):
    # weights 为本层中每个神经元的权重,元素类型为一维的tf.constant,weights的类型是python的列表
    # thresholds 为本层中每个神经元的权重,元素类型为零维的tf.constant,thresholds的类型是python的列表
    def __init__(self, weights, thresholds):
        self.weights = weights
        self.thresholds = thresholds

    # input_value 是输入值, 类型为一维的tf.constant
    # 返回值应为一个 1 维, 长度为n的Tensor, n是本层中神经元的数量
    def computes(self, input_value):
        ans = []
        l = len(self.weights)
        i = 0
        while i < l:
            mp = neuron(self.weights[i], self.thresholds[i])
            mp_out = mp.computes(input_value)
            ans.append(mp_out)
            i += 1
        return tf.constant(ans)

# 模拟一个简单的神经网络
'''
input_value是这个神经网络的输入,类型为一维的tf.constant
wegihtsOfMiddle 是这个神经网络中间层每个神经元的权重, 元素类型为一维的tf.constant,wegihtsOfMiddle的类型是python的列表
thresholdsOfMiddle 是这个神经网络中间层每个神经元的阈值, 元素类型为零维的tf.constant,thresholdsOfMiddle的类型是python的列表
wegihtsOfOut 是这个神经网络输出层每个神经元的权重, 元素类型为一维的tf.constant,wegihtsOfOut 的类型是python的列表
thresholdsOfOut 是这个神经网络输出层每个神经元的阈值, 元素类型为零维的tf.constant,thresholdsOfOut 的类型是python的列表
返回值是一个一维浮点数组 (注意不是Tensor),数组的长度为输出层神经元的数量
'''
def NetWork(input_value, wegihtsOfMiddle, thresholdsOfMiddle, weightsOfOut, thresholdsOfOut):
    hidden = Dense(wegihtsOfMiddle, thresholdsOfMiddle)
    hidden_out = hidden.computes(input_value)
    outter = Dense(weightsOfOut, thresholdsOfOut)
    with tf.Session() as sess:
        result = sess.run(outter.computes(hidden_out))
    return result
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

happylife_mini

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值