# -*- 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