【深度学习_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)

猜你喜欢

转载自blog.csdn.net/oliverchrist/article/details/79395809