Skip to content
Rain Hu's Workspace
Go back

[AI] 3-3. 使用 TensorFlow 與 Keras 函式庫

Rain Hu

建立張量與變數

張量

import tensorflow as tf
x = tf.ones(shape=(2,1))
print(x)

>>> tf.Tensor(
[[1.]
 [1.]], shape=(2, 1), dtype=float32)
y = tf.zeros(shape=(2,1))
print(y)

>>> tf.Tensor(
[[0.]
 [0.]], shape=(2, 1), dtype=float32)
a = tf.constant(((1.,4.),(9.,16.)))
print(a)

>>> tf.Tensor(
[[ 1.  4.]
 [ 9. 16.]], shape=(2, 2), dtype=float32)
x = np.ones((2,2))
x[0, 0] = 0
y = tf.convert_to_tensor(x)
print(y)

>>> tf.Tensor(
[[0. 1.]
 [1. 1.]], shape=(2, 2), dtype=float64)

變數

張量操作

基本數學運算

a = tf.constant(((1.,4.),(9.,16.)))

>>> tf.Tensor(
[[ 1.  4.]
 [ 9. 16.]], shape=(2, 2), dtype=float32)
a = tf.square(a)
print(a)

>>> tf.Tensor(
[[  1.  16.]
 [ 81. 256.]], shape=(2, 2), dtype=float32)
a = tf.sqrt(a)
print(a)

>>> tf.Tensor(
[[ 1.  4.]
 [ 9. 16.]], shape=(2, 2), dtype=float32)
b = tf.ones((2,2))
print(a+b)

>>> tf.Tensor(
[[ 2.  5.]
 [10. 17.]], shape=(2, 2), dtype=float32)
b = tf.constant(((1.,-1.),(-1.,1.)))
c = tf.matmul(a,b)
print(c)

>>> tf.Tensor(
[[-3.  3.]
 [-7.  7.]], shape=(2, 2), dtype=float32)
d = a*b
print(d)

>>> tf.Tensor(
[[ 1. -4.]
 [-9. 16.]], shape=(2, 2), dtype=float32) 

微分


Share this post on:

Previous
[AI] 3-4. 線性迴歸
Next
[AI] 3-2. Keras 介紹