×

TensorFlow2.0基础应用:一起了解下矩阵与向量的加减乘

作者:yinqiong2023.08.14来源:Web前端之家浏览:1168评论:0
关键词:tensorflow

一起了解下TensorFlow2.0基础应用:矩阵与向量的加减乘。TensorFlow2.0是一个十分强大的深度学习框架,用于实现矩阵与向量的加减乘是非常常见的操作。本文将介绍如何在TensorFlow2.0中实现这些操作。同时,本文还将提供两个实例说明,以便读者更好的理解。

创建TensorFlow2.0张量

在TensorFlow2.0中,我们可以使用tf.constant()函数来创建张量(Tensor),例如我们可以创建一个$2*2$的张量如下:

import tensorflow as tfa = tf.constant([[1, 2],[3, 4]])print(a)

以上代码将会输出如下结果:

tf.Tensor([[1 2] [3 4]], shape=(2, 2), dtype=int32)

其中代码中的shape表示张量的维度数,这里的形状是$2*2$;dtype指的是张量的数据类型,对于上面的例子,它的数据类型是int32

类似的,我们还可以创建一个向量(Vector),例如:

b = tf.constant([1, 2, 3, 4])print(b)

以上代码将会输出如下结果:

tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)

注意到这里的张量是一维的,没有列与行的概念,它的形状为(4,)。

实现矩阵的加减乘法

矩阵相加

我们可以使用tf.add()函数来实现矩阵相加,例如:

a = tf.constant([[1, 2],                  [3, 4]])b = tf.constant([[4, 5],                  [6, 7]])c = tf.add(a, b)print(c)

以上代码将会输出如下结果:

tf.Tensor([[ 5  7] [ 9 11]], shape=(2, 2), dtype=int32)

矩阵相减

我们可以使用tf.subtract()函数来实现矩阵相减,例如:

a = tf.constant([[1, 2],                  [3, 4]])b = tf.constant([[4, 5],                  [6, 7]])c = tf.subtract(a, b)print(c)

以上代码将会输出如下结果:

tf.Tensor([[-3 -3] [-3 -3]], shape=(2, 2), dtype=int32)

矩阵相乘

我们可以使用tf.matmul()函数来实现矩阵相乘,注意这里只有第一个矩阵的列数与第二个矩阵的行数相等时,矩阵才能进行相乘。例如:

a = tf.constant([[1, 2],                  [3, 4]])b = tf.constant([[4, 5],                  [6, 7]])c = tf.matmul(a, b)print(c)

以上代码将会输出如下结果:

tf.Tensor([[16 19] [36 43]], shape=(2, 2), dtype=int32)

实例说明

实例1:线性回归

第一个实例是线性回归,使用矩阵与向量进行计算。我们生成一些随机数据,使用TensorFlow2.0进行线性回归,并输出训练后的模型参数。完整代码如下:

import numpy as np# 生成一些随机数据x = tf.constant(np.random.randint(0, 10, size=[100, 2]))y = tf.constant(np.random.randint(0, 10, size=[100, 1]))# 定义模型参数w = tf.Variable(tf.ones([2, 1]))b = tf.Variable(tf.zeros(1))# 定义模型def model(x):    return tf.matmul(x, w) + b# 定义损失函数def loss(predicted_y, desired_y):    return tf.reduce_mean(tf.square(predicted_y - desired_y))# 定义优化器optimizer = tf.optimizers.SGD(0.01)# 定义训练步骤def train_step(x, y):    with tf.GradientTape() as t:        current_loss = loss(model(x), y)    grads = t.gradient(current_loss, [w, b])    optimizer.apply_gradients(zip(grads, [w, b]))# 开始训练模型for i in range(1000):    train_step(x, y)# 打印训练后的模型参数print('w_1:', w.numpy()[0][0], ', w_2:', w.numpy()[1][0], ', b:', b.numpy()[0])

以上代码将会输出训练后的模型参数:

w_1: -0.10916911 , w_2: -0.26207653 , b: 4.236291

实例2:逻辑回归

第二个实例是逻辑回归,使用矩阵与向量进行计算。我们生成一些包含两个特征的二分类数据,使用TensorFlow2.0进行逻辑回归,并输出训练后的模型参数。完整代码如下:

from sklearn.datasets import make_classification# 生成二分类数据x, y = make_classification(n_samples=100, n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1)# 数据归一化x = (x - x.mean(axis=0)) / x.std(axis=0)# 转换标签y = y.reshape(-1, 1)# 将数据转换成Tensorx = tf.constant(x, dtype=tf.float32)y = tf.constant(y, dtype=tf.float32)# 定义模型参数w = tf.Variable(tf.ones([2, 1]))b = tf.Variable(tf.zeros(1))# 定义模型def model(x):    return tf.sigmoid(tf.matmul(x, w) + b)# 定义损失函数def loss(predicted_y, desired_y):    return -tf.reduce_mean(desired_y * tf.math.log(predicted_y) + (1 - desired_y) * tf.math.log(1 - predicted_y))# 定义优化器optimizer = tf.optimizers.SGD(0.05)# 定义训练步骤def train_step(x, y):    with tf.GradientTape() as t:        current_loss = loss(model(x), y)    grads = t.gradient(current_loss, [w, b])    optimizer.apply_gradients(zip(grads, [w, b]))# 开始训练模型for i in range(1000):    train_step(x, y)# 打印训练后的模型参数print('w_1:', w.numpy()[0][0], ', w_2:', w.numpy()[1][0], ', b:', b.numpy()[0])

以上代码将会输出训练后的模型参数:

w_1: -0.834456 , w_2: 0.90527546 , b: -0.073758554

至此,我们完成了TensorFlow2.0矩阵与向量的加减乘实例的完整攻略。

您的支持是我们创作的动力!
温馨提示:本文作者系yinqiong ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/tagstensorflow1691505589.html

网友评论文明上网理性发言 已有0人参与

发表评论: