神经网络实现4位加法器上海大学智能计算系统

 《智能计算系统》书2.11作业

题目:设计一个多层感知器实现4位加法器的功能,即两个4比特输入得到一个4比特输出和一个1比特进位。请自行构造训练集和测试集,完成训练及测试。

        我使用的是TensorFlow 2,需要关闭Eager Execution 实现TensorFlow 1.x 版本中的静态图形编程模型。

# 导入 TensorFlow 库
import tensorflow as tf

# 关闭 Eager Execution 模式
tf.compat.v1.disable_eager_execution()

# 定义输入和输出

inputs = tf.compat.v1.placeholder(tf.float32, shape=[None, 8])
outputs = tf.compat.v1.placeholder(tf.float32, shape=[None, 5])

# 创建一个全连接层和输出层,定义损失函数,使用梯度下降优化损失函数。

# 创建一个全连接层
hidden_layer = tf.keras.layers.Dense(8, activation='relu')(inputs)

# 创建一个输出层
#predictions = tf.keras.layers.Dense(4, activation='sigmoid')(hidden_layer)
predictions = tf.keras.layers.Dense(5, activation='sigmoid')(hidden_layer)
# 定义损失函数
loss = tf.losses.mean_squared_error(outputs, predictions)

# 使用梯度下降法优化损失函数
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.5).minimize(loss)

#训练模型


# 训练模型
with tf.compat.v1.Session() as sess:
  sess.run(tf.compat.v1.global_variables_initializer())
  '''
  # 定义训练数据
  x = [[1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 1]]
  #y = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
  y = [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 1],]'''
  x = []
  y = []
  for i in range(16):
    for k in range(16):
      # 生成两个四位随机数
      #x1 = [random.randint(0, 1) for i in range(4)]
      x1 = bin(i)[2:]
      if len(x1) < 4:
          x1 = "0" * (4 - len(x1)) + x1
      x1 = [int(i) for i in list(x1)]
      
      #x2 = [random.randint(0, 1) for i in range(4)]
      x2 = bin(k)[2:]
      if len(x2) < 4:
          x2 = "0" * (4 - len(x2)) + x2
      x2 = [int(i) for i in list(x2)]
    
    
      # 将两个四位随机数合并成一个八位数
      xi = x1 + x2

     # 计算两个四位随机数的和
      yi = [sum(x) for x in zip(x1, x2)]

      #计算进位
      carry = 0
      for j in range(3, -1, -1):
       yi[j] += carry
       carry = 0
       if yi[j] >= 2:
          yi[j] -= 2
          carry = 1

      #添加进位到输出
      yi.append(carry)
    
      #添加到训练数据中
      x.append(xi)
      y.append(yi)

 # x1 = list(set(x1))
 # x2 = list(set(x2))
  
  for i in range(100):
    # 运行训练步骤
    sess.run(train_step, feed_dict={inputs: x, outputs: y})
    
  # 计算预测值
  #x_predict = [[1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 1]]
  print(x[:10])
  print(y[:10])
  predictions = sess.run(predictions, feed_dict={inputs: x[:10]})
  
  # 打印预测值
  print(predictions)

两个4位加法输入:

一个4位输出和一个进位,前4位代表输出,后1位进位:

将所有两个4位X作为模型输入 

测试结果:

神经网络实现4位加法器上海大学智能计算系统_第1张图片

 

你可能感兴趣的:(神经网络,tensorflow,深度学习)