tensorflow2.0入門操作

開篇

作爲用tensorflow1.4一值沒更新的人來講,本來決定換pytorch,但是看了下tensorflow2的一些簡單操作後,決定再次投入到tensorflow的懷抱。

基礎操作

首先看一些基礎操作

import tensorflow as tf
import numpy as np
tf.__version__
#'2.2.0'

x = [[1.]]
m = tf.matmul(x, x)
print(m)

tf.Tensor([[1.]], shape=(1, 1), dtype=float32)

竟然可以直接打印,之前debug提起session就崩潰,看到現在這麼輕易的print簡直不敢相信

x = tf.constant([[1,9],[3,6]])
x
#<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
#array([[1, 9],
#       [3, 6]], dtype=int32)>

x = tf.add(x, 1)
x
#<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
#array([[ 2, 10],
#       [ 4,  7]], dtype=int32)>

簡直欣喜若狂

在看跟numpy的無縫隙轉換

x.numpy()
#array([[ 2, 10],
#       [ 4,  7]], dtype=int32)

實例demo

迴歸

用一個簡單的數據集演練迴歸

features = pd.read_csv('temps.csv')
#看看數據長什麼樣子
features.head()

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-KkC0ZLq2-1591672453976)(evernotecid://DD492144-9AFF-43C1-9BC0-5A625709FC62/appyinxiangcom/28357599/ENResource/p43)]

字段解釋:

  • year,moth,day,week分別表示的具體的時間
  • temp_2:前天的最高溫度值
  • temp_1:昨天的最高溫度值
  • average:在歷史中,每年這一天的平均最高溫度值
  • actual:這就是我們的標籤值了,當天的真實最高溫度
  • friend:這一列可能是湊熱鬧的,你的朋友猜測的可能值,咱們不管它就好了

數據需要做一些簡單的處理

  • 對於星期獨熱編碼
  • 建立好X和labels
  • 標準化
基於Keras構建網絡模型

一些常用參數已經列出,如下所示:

  • activation:激活函數的選擇,一般常用relu
  • kernel_initializer,bias_initializer:權重與偏置參數的初始化方法,有時候不收斂換種初始化就突然好使了。。。玄學
  • kernel_regularizer,bias_regularizer:要不要加入正則化,
  • inputs:輸入,可以自己指定,也可以讓網絡自動選
  • units:神經元個數

按順序構造網絡模型

model = tf.keras.Sequential()
model.add(layers.Dense(16))
model.add(layers.Dense(32))
model.add(layers.Dense(1))
#compile相當於對網絡進行配置,指定好優化器和損失函數等
model.compile(optimizer=tf.keras.optimizers.SGD(0.001),
             loss='mean_squared_error')
model.fit(input_features, labels, validation_split=0.25, epochs=10, batch_size=64)

看下最後一次訓練結果

Epoch 100/100
5/5 [==============================] - 0s 7ms/step - loss: 26.3111 - val_loss: 36.1550

看下模型參數
model.summary()
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-pNOxOkXz-1591672453978)(evernotecid://DD492144-9AFF-43C1-9BC0-5A625709FC62/appyinxiangcom/28357599/ENResource/p44)]
240=1416+16240=14*16+16
544=1632+32544=16*32+32
33=321+133=32*1+1

調參
model = tf.keras.Sequential()
model.add(layers.Dense(16,kernel_initializer='random_normal'))
model.add(layers.Dense(32,kernel_initializer='random_normal'))
model.add(layers.Dense(1,kernel_initializer='random_normal'))

model.compile(optimizer=tf.keras.optimizers.SGD(0.001),
             loss='mean_squared_error')
model.fit(input_features, labels, validation_split=0.25, epochs=100, batch_size=64)

Epoch 100/100
5/5 [==============================] - 0s 7ms/step - loss: 35.6163 - val_loss: 19.1636

加入正則化懲罰項
model = tf.keras.Sequential()
model.add(layers.Dense(16,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03)))
model.add(layers.Dense(32,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03)))
model.add(layers.Dense(1,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03)))

model.compile(optimizer=tf.keras.optimizers.SGD(0.001),
             loss='mean_squared_error')
model.fit(input_features, labels, validation_split=0.25, epochs=100, batch_size=64)
預測模型結果
predict = model.predict(input_features)

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-QKIDPbxr-1591672453979)(evernotecid://DD492144-9AFF-43C1-9BC0-5A625709FC62/appyinxiangcom/28357599/ENResource/p45)]

完整代碼github

分類

數據使用mnist數據集

import tensorflow as tf
from tensorflow.keras import layers

model = tf.keras.Sequential()
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

model.compile(optimizer=tf.keras.optimizers.Adam(0.005),
             loss=tf.keras.losses.SparseCategoricalCrossentropy(),
             metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])


model.fit(x_train, y_train, epochs=5, batch_size=64,
          validation_data=(x_valid, y_valid))

782/782 [==============================] - 2s 3ms/step - loss: 0.1102 - sparse_categorical_accuracy: 0.9666 - val_loss: 0.1491 - val_sparse_categorical_accuracy: 0.9585

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章