tensorflow学习笔记(北京大学) tf4_8_forward.py 完全解析

#coding:utf-8
#tensorflow学习笔记(北京大学) tf4_8_forward.py 完全解析  
#QQ群:476842922(欢迎加群讨论学习)
#如有错误还望留言指正,谢谢
#前向传播就是搭建网络
import tensorflow as tf

#定义神经网络的输入、参数和输出,定义前向传播过程 
def get_weight(shape, regularizer):#(shape:W的形状,regularizer正则化)
	w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)#赋初值,正态分布权重
	tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))#把正则化损失加到总损失losses中
	return w#返回w
#tf.add_to_collection(‘list_name’, element):将元素element添加到列表list_name中

def get_bias(shape):  #偏执b
    b = tf.Variable(tf.constant(0.01, shape=shape)) #偏执b=0.01
    return b#返回值
	
def forward(x, regularizer):#前向传播
	
	w1 = get_weight([2,11], regularizer)#设置权重	
	b1 = get_bias([11])#设置偏执
	y1 = tf.nn.relu(tf.matmul(x, w1) + b1)#计算图

	w2 = get_weight([11,1], regularizer)#设置权重
	b2 = get_bias([1])#设置偏执
	y = tf.matmul(y1, w2) + b2 #计算图
	
	return y#返回值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在神经网络训练完成后,我们可以使用模型对新的输入数据进行预测。以下是使用 TensorFlow 进行简单神经网络训练和测试的示例代码: ```python import tensorflow as tf # 定义输入数据 x = tf.placeholder(tf.float32, [None, input_size]) # 定义模型参数 W = tf.Variable(tf.zeros([input_size, num_classes])) b = tf.Variable(tf.zeros([num_classes])) # 定义模型 y = tf.nn.softmax(tf.matmul(x, W) + b) # 定义损失函数 y_ = tf.placeholder(tf.float32, [None, num_classes]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 定义优化器 train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(num_iterations): batch_xs, batch_ys = get_next_batch(train_data, train_labels, batch_size) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 测试模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy: ", sess.run(accuracy, feed_dict={x: test_data, y_: test_labels})) ``` 在训练完成后,我们可以使用 `sess.run()` 函数来获取模型的输出。例如,如果我们想要对一个新的数据样本进行预测,我们可以将其传递给 `sess.run()` 函数的 `feed_dict` 参数,并获取模型的输出 `y`。下面是一个简单的示例: ```python # 定义要预测的数据 new_data = [[5.1, 3.5, 1.4, 0.2]] # 获取预测结果 prediction = sess.run(y, feed_dict={x: new_data}) # 打印预测结果 print(prediction) ``` 在上面的代码中,我们将 `new_data` 作为输入数据传递给模型,并使用 `sess.run()` 函数获取模型的输出 `y`。然后,我们打印预测结果即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值