如何使用 TensorFlow 实现逻辑回归函数?
TensorFlow 是 Google 提供的一个机器学习框架。它是一个开源框架,与 Python 结合使用,用于实现算法、深度学习应用程序等等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。
可以使用以下代码行在 Windows 上安装“tensorflow”包:
pip install tensorflow
张量是 TensorFlow 中使用的一种数据结构。它有助于连接流图中的边。此流图称为“数据流图”。张量只不过是多维数组或列表。它们可以使用三个主要属性来识别
秩 - 它告诉我们张量的维度。可以理解为张量的阶数或已定义的张量中的维度数。
类型 - 它告诉我们与张量元素关联的数据类型。它可以是一维、二维或 n 维张量。
形状 - 它是行数和列数的总和。
我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助通过浏览器运行 Python 代码,并且无需任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。
以下是一个示例:
示例
def logistic_reg(x): return tf.nn.softmax(tf.matmul(x, A) + b) def cross_entropy(y_pred, y_true): y_true = tf.one_hot(y_true, depth=num_classes) y_pred = tf.clip_by_value(y_pred, 1e-9, 1.) return tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred),1)) def accuracy_val(y_pred, y_true): correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64)) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) optimizer = tf.optimizers.SGD(learning_rate) def run_optimization(x, y): with tf.GradientTape() as g: pred = logistic_reg(x) loss = cross_entropy(pred, y) gradients = g.gradient(loss, [A, b]) optimizer.apply_gradients(zip(gradients, [A, b]))
输出
Once the functions are called, the optimization process begins. Here, we are using the stochastic gradient descent optimizer. This means, the optimal values for the ‘weight’ and ‘bias’ are tried to be computed. Once these gradients are computed, the ‘weight’ and ‘bias’ values are updated.
解释
定义了一个名为“logistic_reg”的函数,该函数给出输入数据的 softmax 值。
它将 logits 标准化为包含概率分布。
定义了交叉熵损失函数,它将标签编码为独热向量。
预测值被格式化以减少 log(0) 错误。
需要计算准确性指标,因此定义了一个函数。
定义了随机梯度下降优化器。
定义了一个用于优化的函数,该函数计算梯度并更新权重和偏差的值。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP