Tensorflo函数(持续扩充)

本文介绍了TensorFlow中几个关键的函数用法,包括tf.clip_by_value限制张量值范围,tf.reduce_mean计算平均值,交叉熵函数如sigmoid_cross_entropy_with_logits等,tf.matmul进行矩阵乘法,以及tf.where和tf.greater的条件判断,还有学习率衰减函数tf.train.exponential_decay,以及tf.argmax用于找到最大值的索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tensorflow函数用法(持续扩充)

1. tf.clip_by_value

tf.clip\_by\_value(v,min,max):
给定一个张量v,将张量v中地每一个元素压缩到[min,max]的值域内。(小于min的置为min,大于max的置为max)。

2. tf.reduce_mean

沿着张量的指定的轴(某一维度),计算张量中元素的平均值。

#Computes the mean of elements across dimensions of a tensor
def reduce_mean(input_tensor,
	                axis=None,
	                keepdims=None,
	                name=None,
	                reduction_indices=None,
	                keep_dims=None):  

Args:

  _ input_tensor : The tensor to reduce. Should have numeric type.
  axis : The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)].
  
keepdims : If true, retains reduced dimensions with length 1.
  _ name : A name for the operation (optional).
  _ reduction_indices : The old (deprecated) name for axis.
  _ keep_dims : Deprecated alias for keepdims.

Returns:
  The reduced tensor.

  x = tf.constant([1, 0, 1, 0])  
  tf.reduce_mean(x)  # 0  
  y = tf.constant([1., 0., 1., 0.])  
  tf.reduce_mean(y)  # 0.5

  x = tf.constant([[1., 1.], [2., 2.]])
  tf.reduce_mean(x)  # 1.5
  tf.reduce_mean(x, 0)  # [1.5, 1.5],以横轴为基准,对横轴每一维所包含的列元素求平均。简单来说,对行(第0维)做压缩。
  tf.reduce_mean(x, 1)  # [1.,  2.],压缩列(第1维)。

3. cross_entropy(交叉熵)

Tensorflow四种交叉熵函数

  • tf.nn.sigmoid_cross_entropy_with_logits
  • tf.nn.softmax_cross_entropy_with_logits
  • tf.nn.sparse_softmax_cross_entropy_with_logits
  • tf.nn.weighted_cross_entropy_with_logits

4. tf.matmul(v1,v2):

矩阵相乘,与*不同。
*的结果为每个元素对应位置上的乘积
matmul为矩阵相乘

5. tf.where/tf.greater

import tensorflow as tf 
v1=tf.constant([1.,2.,3.]) 
v2=tf.constant([3.,1.,4.]) 
with tf.Session() as sess:
    Great=tf.greater(v1,v2)
    print (sess.run(Great))
    #[False  True False]
    Where=tf.where(Great,v1,v2)
    print(Where)
    #Tensor("Select:0", shape=(3,), dtype=float32)
    print(sess.run(Where))
    #[ 3.  2.  4.]

6. tf.train.exponential_decay:

#Applies exponential decay to the learning rate.
def exponential_decay(learning_rate,
                      global_step,
                      decay_steps,
                      decay_rate,
                      staircase=False,
                      name=None):  

Returns:
  The function returns the decayed learning rate. It is computed as:

  decayed_learning_rate = learning_rate *
                          decay_rate ^ (global_step / decay_steps)  

Args:

  • learning_rate: A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
  • global_step: A scalar int32 or int64 Tensor or a Python number. Global step to use for the decay computation. Must not be negative.
  • decay_steps: A scalar int32 or int64 Tensor or a Python number. Must be positive. See the decay computation above.
  • decay_rate: A scalar float32 or float64 Tensor or a Python number. The decay rate. staircase: Boolean. If True decay the learning rate at discrete intervals
  • name: String. Optional name of the operation. Defaults to ‘ExponentialDecay’.

7. tf.argmax:

#Returns the index with the largest value across dimensions of a tensor
def argmax(input,
           axis=None,
           name=None,
           dimension=None,
           output_type=dtypes.int64):

说明:tf\.argmax(V,1):
 V代表一个张量1表示选取最大值的操作仅在第1个维度上进行,即只在每一行选取最大值对应的下标
实例:

import tensorflow as tf 
V=tf.constant([[1,2,3],[2,3,4]])
Max=tf.argmax(V,1)
print(Max.eval(session=tf.Session()))
#[2 2] 结果存储的是每一行的最大值对应的下标值
Max2=tf.argmax(V,0)
print(Max2.eval(session=tf.Session()))
#[1 1 1] 结果存储的是每一列的最大值对应的下标值
### 欠拟合的原因 欠拟合的主要原因是模型无法充分捕捉到数据中的模式,具体表现为训练误差和测试误差都较高,在数学上体现为高偏差(high bias)。这种情况可能由于以下几个因素引起: - **模型复杂度过低**:如果使用的模型过于简单,则难以表达复杂的函数关系[^2]。 - **特征不足**:输入的数据缺乏足够的信息量来描述目标变量的变化规律。 ### 过拟合的解决方法 #### 正则化 正则化是一种通过向损失函数添加惩罚项的方式减少参数值大小的技术。它能够有效抑制模型权重过大带来的波动效应,降低模型复杂度并提高其泛化性能。常见的有L1正则化和L2正则化两种形式: ```python from tensorflow.keras import regularizers model.add(Dense(64, input_dim=64, kernel_regularizer=regularizers.l2(0.01))) ``` #### Dropout Dropout技术是在每次更新网络时随机忽略一部分神经元的操作方式,以此达到模拟多个子网络的效果,并最终取平均作为预测结果。这种方法有助于缓解因某些特定连接权值过高而导致的过拟合现象: ```python from tensorflow.keras.layers import Dropout model.add(Dropout(0.5)) ``` #### 数据增强 对于图像分类等问题而言,可以通过旋转、缩放等方式扩充原始样本集合规模,使得模型接触到更多样化的实例组合,进而提升应对未知情况的能力. #### 提前终止 (Early Stopping) 提前终止策略是指在训练期间持续监测验证集上的表现指标变化趋势;一旦发现该指标不再继续改进甚至恶化,则立即中断整个过程以防进一步加剧过拟合状况的发生[^1]. ```python from keras.callbacks import EarlyStopping early_stopping_monitor = EarlyStopping( monitor='val_loss', patience=3) history = model.fit(X_train, y_train, validation_split=0.2, epochs=30, callbacks=[early_stopping_monitor]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值