zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

TensorFlow入门--构建神经网络

入门神经网络 -- 构建 Tensorflow
2023-09-14 09:14:57 时间

‘’’
前面一直卡在TypeError: List of Tensors when single Tensor expected
这个tf1的会话机制确实恶心 我明白了tf2的伟大
‘’’

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

# 模拟一个 M-P 神经元
class neuron(object):

    # 构造函数
    # weight为本神经元的权重,类型为一维的tf.constant
    # threshold 是这个神经元的阈值, 类型为零维的tf.constant
    def __init__(self, weight, threshold):
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
        self.weight = weight
        self.threshold = threshold 
    # ********** End **********#

    # 计算函数
    # input_value 是输入值, 类型为一维的tf.constant
    # 返回值是一个浮点数
    def computes(self, input_value):
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
        total = tf.reduce_sum(tf.multiply(self.weight, input_value)) - self.threshold
        with tf.Session() as sess:
            return sess.run(tf.nn.relu(total))
    # ********** End **********#

# 模拟神经网络中的一层
class Dense(object):
    
    # 构造函数
    # weights 为本层中每个神经元的权重,元素类型为一维的tf.constant,weights的类型是python的列表
    # thresholds 为本层中每个神经元的权重,元素类型为零维的tf.constant,thresholds的类型是python的列表
    def __init__(self, weights, thresholds):
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
        size = len(weights)
        self.neurons = []
        for i in range(size):
            self.neurons.append(neuron(weights[i], thresholds[i]))
    # ********** End **********#

    # 计算函数
    # input_value 是输入值, 类型为一维的tf.constant
    # 返回值应为一个 1 维, 长度为n的Tensor, n是本层中神经元的数量
    def computes(self, input_value):
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
        L = []
        size = len(self.neurons)
        for i in range(size):
            L.append(self.neurons[i].computes(input_value))
        return tf.constant(L)
    # ********** End **********#

# 模拟一个简单的神经网络
# 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):
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    middle = Dense(wegihtsOfMiddle, thresholdsOfMiddle)
    out = Dense(weightsOfOut, thresholdsOfOut)
    return out.computes(middle.computes(input_value)).eval()
    # ********** End **********#