【深度学习_2.3_1】神经网络之TensorFlow初步应用

导入相关类库

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict


%matplotlib inline
np.random.seed(1)

TensorFlow计算损失函数样例


代码实现:

y_hat = tf.constant(36, name='y_hat')            # Define y_hat constant. Set to 36.
y = tf.constant(39, name='y')                    # Define y. Set to 39


loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss


init = tf.global_variables_initializer()         # When init is run later (session.run(init)),
                                                 # the loss variable will be initialized and ready to be computed
with tf.Session() as session:                    # Create a session and print the output
    session.run(init)                            # Initializes the variables
    print(session.run(loss))                     # Prints the loss

注:只是定义了损失函数loss,这并不能计算损失函数;需要执行init=tf.global_variables_initializer(),才能计算

placeholder代码样例

创建placeholder时,不需要传入值,当执行这个变量时才需要传入具体值

x = tf.placeholder(tf.int64, name = 'x')
print(sess.run(2 * x, feed_dict = {x: 3}))
sess.close()

linear function代码实现

代码实现公式:Y=WX+b

    X = tf.constant(np.random.randn(3, 1), name="X")
    W = tf.constant(np.random.randn(4, 3), name="W")
    b = tf.constant(np.random.randn(4, 1), name="b")
    Y = tf.add(tf.matmul(W,X),b)

执行:

    sess = tf.Session()
    result = sess.run(Y)

    sess.close()

sigmoid函数的代码实现

定义占位符:

x = tf.placeholder(tf.float32, name="x")

代码定义sigmoid:

sigmoid = tf.sigmoid(x)

执行:

with tf.Session() as session:

result = session.run(sigmoid, feed_dict = {x: z})

代码实现损失函数


定义占位符:

    z = tf.placeholder(tf.float32, name="z")
    y = tf.placeholder(tf.float32, name="y")

定义计算损失函数:

cost = tf.nn.sigmoid_cross_entropy_with_logits(logits = z,  labels = y)

执行:

sess = tf.Session()

cost = sess.run(cost,feed_dict={z:logits,y:labels})

sess.close()

矩阵的转换

代码实现:tf.one_hot(labels, depth, axis)

初始化0、1矩阵

  • tf.zeros(shape)
  • tf.ones(shape)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值