python如何增加隐藏层_TensorFlow感知器隐藏层

这篇博客介绍了如何在TensorFlow中构建带有隐藏层的感知器,通过实例展示了隐藏层的学习过程,包括网络结构、参数训练和损失函数的最小化,用于函数逼近。
摘要由CSDN通过智能技术生成

本篇文章帮大家学习TensorFlow感知器隐藏层,包含了TensorFlow感知器隐藏层使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。

在本章中将重点关注我们将要从已知的一组点x和f(x)中学习的网络。单个隐藏层将构建这个简单的网络。

用于解释感知器隐藏层的代码如下所示 -

#Importing the necessary modules

import tensorflow as tf

import numpy as np

import math, random

import matplotlib.pyplot as plt

np.random.seed(1000)

function_to_learn = lambda x: np.cos(x) + 0.1*np.random.randn(*x.shape)

layer_1_neurons = 10

NUM_points = 1000

#Training the parameters

batch_size = 100

NUM_EPOCHS = 1500

all_x = np.float32(np.random.uniform(-2*math.pi, 2*math.pi, (1, NUM_points))).T

np.random.shuffle(all_x)

train_size = int(900)

#Training the first 700 points in the given set x_training = all_x[:train_size]

y_training = function_to_learn(x_training)

#Training the last 300 points in the given set x_validation = all_x[train_size:]

y_validation = function_to_learn(x_validation)

plt.figure(1)

plt.scatter(x_training, y_training, c = 'blue', label = 'train')

plt.scatter(x_validation, y_validation, c = 'pink', label = 'validation')

plt.legend()

plt.show()

X = tf.placeholder(tf.float32, [None, 1], name = "X")

Y = tf.placeholder(tf.float32, [None, 1], name = "Y")

#first layer

#Number of neurons = 10

w_h = tf.Variable(

tf.random_uniform([1, layer_1_neurons], minval = -1, maxval = 1, dtype = tf.float32))

b_h = tf.Variable(tf.zeros([1, layer_1_neurons], dtype = tf.float32))

h = tf.nn.sigmoid(tf.matmul(X, w_h) + b_h)

#output layer

#Number of neurons = 10

w_o = tf.Variable(

tf.random_uniform([layer_1_neurons, 1], minval = -1, maxval = 1, dtype = tf.float32))

b_o = tf.Variable(tf.zeros([1, 1], dtype = tf.float32))

#build the model

model = tf.matmul(h, w_o) + b_o

#minimize the cost function (model - Y)

train_op = tf.train.AdamOptimizer().minimize(tf.nn.l2_loss(model - Y))

#Start the Learning phase

sess = tf.Session() sess.run(tf.initialize_all_variables())

errors = []

for i in range(NUM_EPOCHS):

for start, end in zip(range(0, len(x_training), batch_size),

range(batch_size, len(x_training), batch_size)):

sess.run(train_op, feed_dict = {X: x_training[start:end], Y: y_training[start:end]})

cost = sess.run(tf.nn.l2_loss(model - y_validation), feed_dict = {X:x_validation})

errors.append(cost)

if i%100 == 0:

print("epoch %d, cost = %g" % (i, cost))

plt.plot(errors,label='MLP Function Approximation') plt.xlabel('epochs')

plt.ylabel('cost')

plt.legend()

plt.show()

以下是功能层近似的表示(输出) -

这里有两个数据以W的形状表示。两个数据是:train和validation,它们在图例中的不同颜色表示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是实现多感知器识别手写数字的 TensorFlow 代码: ```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 加载MNIST数据集 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 定义超参数 learning_rate = 0.01 num_steps = 1000 batch_size = 128 display_step = 100 # 定义网络参数 n_hidden_1 = 256 # 第一隐藏神经元个数 n_hidden_2 = 256 # 第二隐藏神经元个数 num_input = 784 # MNIST数据集每张图片的像素个数(28*28) num_classes = 10 # MNIST数据集的类别个数(0-9) # 定义输入输出占位符 X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float", [None, num_classes]) # 定义权重和偏置变量 weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([num_classes])) } # 定义多感知器网络模型 def neural_net(x): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # 构建模型 logits = neural_net(X) # 定义损失函数和优化器 loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # 定义评估模型的准确率 correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # 初始化变量 init = tf.global_variables_initializer() # 开始训练模型 with tf.Session() as sess: sess.run(init) for step in range(1, num_steps+1): batch_x, batch_y = mnist.train.next_batch(batch_size) sess.run(train_op, feed_dict={X: batch_x, Y: batch_y}) if step % display_step == 0 or step == 1: # 计算损失函数和准确率,并输出 loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y}) print("Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) print("Optimization Finished!") # 计算测试集准确率 print("Testing Accuracy:", \ sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels})) ``` 这段代码使用了 TensorFlow 中的 `tf.layers` API 来构建多感知器网络模型,使用交叉熵损失函数和 Adam 优化器进行训练,最后计算模型在测试集上的准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值