求梯度流程
1) 在with中使用tf.gradienttape()生成可計算梯度的物件
2) 使用tensor構建loss
3) 使用1)的物件計算梯度
import tensorflow as tf
x = tf.constant([[1, 2, 3], [2, 2, 3]])
print("sum of all x:", tf.reduce_sum(x, axis=none)) # 不指定axis則求所有元素的和
print("sum of x(column):", tf.reduce_sum(x, axis=0)) # 在第1個維度(行)上求,即求每一列的和
print("sum of x(row):", tf.reduce_sum(x, axis=1)) # 在第2個維度(行)上求,即求每一行的和
'''sum of all x: tf.tensor(13, shape=(), dtype=int32)
sum of x(column): tf.tensor([3 4 6], shape=(3,), dtype=int32)
sum of x(row): tf.tensor([6 7], shape=(2,), dtype=int32)'''
import tensorflow as tf
w = tf.variable(tf.constant(5, dtype=tf.float32))
lr = 0.18
epoch = 20
for epoch in range(epoch): # for epoch 定義頂層迴圈,表示對資料集迴圈epoch次,此例資料集資料僅有1個w,初始化時候constant賦值為5,迴圈40次迭代。
with tf.gradienttape(persistent=true) as tape: # with結構到grads框起了梯度的計算過程。
loss = tf.square(w + 1)
grads = tape.gradient(loss, w) # 為了求二階導數,必須寫在with內
grads2 = tape.gradient(grads, w) #二次求導(寫不寫在with內均可)
print('grads 2nd:', grads2)
import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)
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[0].numpy(), element[1])
#[out:]12 tf.tensor(0, shape=(), dtype=int32)
shape of y: (1,3), then
tf.squeeze(y) -> shape (3,)
tf.squeeze(y, axis=0) -> shape (3,)
tf.squeeze(y, axis=1) -> error
import tensorflow as tf
import numpy as np
test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print("每一列的最大值的索引:", tf.argmax(test, axis=0)) # 返回每一列最大值的索引
print("每一行的最大值的索引", tf.argmax(test, axis=1)) # 返回每一行最大值的索引
Linux筆記第一課
一 開源軟體 開源軟體的特點就是把軟體程式與源 檔案一起打包提供給使用者,讓使用者在不受限制地使用某個軟體功能的基礎上還可以按需進行修改,或編製成衍生產品再發布出去。使用者具有使用自由 修改自由 重新發布自由以及建立衍生品的自由。世界上現在有60多種被開源促進組織 open source initi...
linuxprobe第一課 筆記
apache來自於印第安語,力量無窮 mpl mozilla public license,mozilla公共許可 許可協議 相較於gpl許可協議,mpl更加注重對開發者的源 需求和收益之間的平衡。mit massachusetts institute of technology 許可協議 目前限制...
sql第一課筆記
雖然之前也是學習過sql server資料庫,但是也是忘記得差不多了。現在重新撿起來,安裝一次資料庫練習,使用的是mysql.第一課是最簡單的建立,修改,檢視,刪除資料庫 mysql 有密碼之後在命令列登陸 用的是 shell mysql u root p 提示輸入密碼 登陸成功之後,把提示符mys...