TensorFlow-简单常见函数

这篇博客展示了TensorFlow的基础操作,包括常量、张量的创建、数学运算(如次方、平方、开方)、矩阵乘法以及变量的自减。还介绍了如何构建数据集,对特征和标签进行配对,以及使用独热编码处理标签。此外,文章还涵盖了梯度计算、softmax函数的应用,确保模型输出符合概率分布。最后,讨论了变量的更新操作和索引选择在数组中的应用。
摘要由CSDN通过智能技术生成

import tensorflow as tf
a = tf.fill([1,2],3.)
print("a:",a)
print("a的次方:",tf.pow(a,3))
print("a的平方:",tf.square(a))
print("a的开放:",tf.sqrt(a))
"""
a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
a的次方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
a的开放: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)
"""

import tensorflow as tf
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print("a:",a)
print("b:",b)
print("a*b:",tf.matmul(a,b))

"""
a: tf.Tensor(
[[1. 1.]
 [1. 1.]
 [1. 1.]], shape=(3, 2), dtype=float32)
b: tf.Tensor(
[[3. 3. 3.]
 [3. 3. 3.]], shape=(2, 3), dtype=float32)
a*b: tf.Tensor(
[[6. 6. 6.]
 [6. 6. 6.]
 [6. 6. 6.]], shape=(3, 3), dtype=float32)
"""

把特征和标签配对。

import tensorflow as tf
features = tf.constant([12,23,10,17])
labels = tf.constant([0,1,1,0])
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
for element in dataset:
    print(element)
"""
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
"""

实现函数对参数的求导运算。

import tensorflow as tf
with tf.GradientTape() as tape:
    x = tf.Variable(tf.constant(3.0))
    y = tf.pow(x,2)
grad = tape.gradient(y,x)
print(grad)

"""
tf.Tensor(6.0, shape=(), dtype=float32)
"""

可以枚举出每一个元素,并在元素前加上索引号。

seq = ['one','two','three']
for i,element in enumerate(seq):
    print(i,element)

"""
0 one
1 two
2 three
"""

常用用独热编码表示标签,

import tensorflow as tf
classes = 3
labels = tf.constant([1,0,2])#输入的元素最小值为0,最大值为2
output = tf.one_hot(labels,depth=classes) #(待转换数据,分几类)
print("result of labels1:",output)

"""
result of labels1: tf.Tensor(
[[0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)
"""

在前向传播过程中,输出的值符合概率分布,才能与独热码进行比较,因此,用softmax,让输出的值符合概率分布,结果为0.256,0.695,0.048,它们的和为1.

0.256表示为第0类鸢尾花的概率是25.6%

softmax是让n分类的n个输出,符合概率分布,概率值在0-1之间,和为1.

import tensorflow as tf
y = tf.constant([1.01,2.01,-0.66])
y_pro = tf.nn.softmax(y)
print("After softmax,y_pro is :",y_pro)#y_pro符合概率分布
print("The sum of y_pro:",tf.reduce_sum(y_pro)) #通过softmax后,所有概率加起来和为1

"""
After softmax,y_pro is : tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)
"""

import tensorflow as tf
x = tf.Variable(4)
x.assign_sub(1) #自减操作
print("x:",x)  #4-1=3  

"""
x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
"""

import numpy as np
import tensorflow as tf
test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
print("test:\n",test)
print("每一列的最大值的索引:",tf.argmax(test,axis=0))
print("每一行的最大值索引:",tf.argmax(test,axis=1))

"""
test:
 [[1 2 3]
 [2 3 4]
 [5 4 3]
 [8 7 2]]
每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64)
每一行的最大值索引: tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
"""

 

TensorFlow是一个流行的开源机器学习工具包,它提供了许多预先定义的损失函数,例如交叉熵损失、均方误差损失等。但是,在一些场景下,我们可能需要自定义损失函数以满足特定的任务要求。 创建自定义损失函数的步骤如下: 1. 采用TensorFlow的Keras API来定义损失函数。开发者可以通过继承tensorflow.keras.losses.Loss类来定义自己的损失函数。在这个类中,我们必须实现call方法,它接收真实值和预测值,并返回批量的平均损失。 2. 在调用模型的编译函数时,将该自定义损失函数的名称传递给“loss”参数。 以下代码展示了一个简单的自定义损失函数的实例: ``` python import tensorflow as tf from tensorflow.keras import backend as K class CustomLoss(tf.keras.losses.Loss): def __init__(self, alpha, **kwargs): super().__init__(**kwargs) self.alpha = alpha def call(self, y_true, y_pred): squared_difference = tf.square(y_true - y_pred) return K.mean(squared_difference,axis=-1) + self.alpha * K.mean(y_pred,axis=-1) model = tf.keras.models.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam',loss=CustomLoss(alpha=0.1)) ``` 在上述代码中,我们定义了一个自定义损失函数CustomLoss。它采用真实值和预测值作为输入,计算出平均损失,并加上一个可控的惩罚项alpha * mean(y_pred)。 最后我们使用这个自定义损失函数来编译了一个包含两个全连接层的神经网络模型。 总之,自定义损失函数TensorFlow平台的常见实践之一,至于要采用何种损失函数,则取决于具体的任务及其相关的性能需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值