tensorflow2.0學習筆記(一)


一、線性回歸

1、庫:tensorflow,pandas,matplotlib.pyplot

2、其他函數:data = pd.read_csv('路徑') 讀取csv格式文件

     data.head() 讀取前五行

     plt.scatter(data.Education,data.Income)#繪制散點圖

3、搭建模型:

序列式模型:keras.Sequential()

定義模型

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1,input_shape=(1,))) #全連接層,表示ax+b

model.summary()#顯示模型結構

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 1)                 2         
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
_________________________________________________________________

模型編譯,定義優化器和損失函數

model.compile(optimizer='adam',
             loss='mse'
             )#編譯

模型訓練,數據輸入,設置訓練輪數

history = model.fit(x,y,epochs=5000)

模型預測

model.predict(x)
model.predict(pd.Series([20]))

二、多層感知器

1、目的:解決xor異或問題,加強模型的擬合能力

2、庫:

import tensofow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

3、處理數據函數

data = pd.read_csv('F:/python_file/tf2exc/Advertising.csv')
x=data.iloc[:,1:-1]#第二列-倒數第二列
y = data.iloc[:,-1]#倒數第一列

4、模型搭建

序列式模型 keras.Sequential()

定義模型

model=tf.keras.Sequential(
[tf.keras.layers.Dense(10,input_shape=(3,),activation='relu'),    #第一層需要聲明shape
 tf.keras.layers.Dense(1)]
)

編譯模型

model.compile(optimizer='adam',
             loss='mse')

訓練模型

model.fit(x,y,epochs=500)

預測模型

test = data.iloc[:10,1:-1]
model.predict(test)

三、邏輯回歸(分類)

1、庫

import tensofow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

2、模型搭建

序列式模型 keras.Sequential()

定義模型

model=tf.keras.Sequential()
model.add(tf.keras.layers.Dense(10,input_shape=(15,),activation='relu'))
model.add(tf.keras.layers.Dense(5,activation='relu'))
model.add(tf.keras.layers.Dense(1,activation='sigmoid')

編譯模型

model.compile(optimizer='adam',
             loss='binary_crossentropy',
             metrics=['acc'])

訓練模型

history = model.fit(x,y,epochs=500)

查看history鍵名

history.history.keys()

可視化loss,acc

plt.plot(history.epoch,history.history.get('loss'))
plt.plot(history.epoch,history.history.get('acc'))

模型預測

model.predict(x)

四、softmax多分類

1、庫:

import tensofow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline

2、處理數據函數

(train_image,train_label),(test_image,test_label) = tf.keras.datasets.fashion_mnist.load_data()
train_image.shape#訓練圖像形狀
train_label #展示訓練標簽
test_image.shape,test_label.shape #測試集形狀
plt.imshow(train_image[0]#展示第一張圖
#數據歸一化
train_image = train_image/255
test_image = test_image/255
#one-hot編碼label
train_label_onehot = tf.keras.utils.to_categorical(train_label)
test_label_onehot = tf.keras.utils.to_categorical(test_label)

3、模型搭建

序列式模型 keras.Sequential()

定義模型

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))#28*28
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dense(96,activation='relu'))
model.add(tf.keras.layers.Dense(48,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))

編譯模型

model.compile(optimizer='adam',
             loss='sparse_categorical_crossentropy',#label用數字編碼
             metrics=['acc'])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
             loss='categorical_crossentropy',#label用onehot編碼,即有幾類,就用一維幾列的向量表示,5類中第一類,label表示為[1,0,0,0,0]
             metrics=['acc'])

訓練模型

history=model.fit(train_image,train_label_onehot,epochs=10,validation_data=(test_image,test_label_onehot))

 

預測模型

predict = model.predict(test_image)
np.argmax(predict[0])#取出第一張圖片預測值最大值的索引,即預測為第幾

可視化訓練過程

history.history.keys()
#dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])
#繪制訓練損失和驗證損失的折線圖
plt.plot(history.epoch, history.history.get('loss'),label='loss')
plt.plot(history.epoch, history.history.get('val_loss'),label='val_loss')
plt.legend()
#繪制訓練精度和驗證精度的折線圖
plt.plot(history.epoch, history.history.get('acc'),label='acc')
plt.plot(history.epoch, history.history.get('val_acc'),label='val_acc')
plt.legend()

簡單數據用簡單網絡,往往學習到更好的關鍵特征

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))#28*28
model.add(tf.keras.layers.Dense(32,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
             loss='categorical_crossentropy',
             metrics=['acc'])#label用onehot編碼


history=model.fit(train_image,train_label_onehot,epochs=10,validation_data=(test_image,test_label_onehot))


plt.plot(history.epoch, history.history.get('acc'),label='acc')
plt.plot(history.epoch, history.history.get('val_acc'),label='val_acc')
plt.legend()

 

五、函數式api

庫:

import tensorflow as tf
import pandas as pd
import numpy as np
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline

數據處理

fashion_mnist = keras.datasets.fashion_mnist
(train_image,train_label),(test_image,test_label) = fashion_mnist.load_data()

train_image = train_image/255.0
test_image = test_image/255.0

搭建模型

定義層,輸入、輸出加入Model

input1 = keras.Input(shape=(28,28))
input2 = keras.Input(shape=(28,28))
x1 = keras.layers.Flatten()(input1)
x2 = keras.layers.Flatten()(input2)
x = keras.layers.concatenate([x1,x2])
x = keras.layers.Dense(32,activation='relu')(x)
x = keras.layers.Dropout(0.5)(x)
x = keras.layers.Dense(64,activation='relu')(x)
output = keras.layers.Dense(1,activation='sigmoid')(x)
model = keras.Model(inputs=[input1,input2],outputs=output)

model.summary()


Model: "model_3"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_4 (InputLayer)            [(None, 28, 28)]     0                                            
__________________________________________________________________________________________________
input_5 (InputLayer)            [(None, 28, 28)]     0                                            
__________________________________________________________________________________________________
flatten_4 (Flatten)             (None, 784)          0           input_4[0][0]                    
__________________________________________________________________________________________________
flatten_5 (Flatten)             (None, 784)          0           input_5[0][0]                    
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 1568)         0           flatten_4[0][0]                  
                                                                 flatten_5[0][0]                  
__________________________________________________________________________________________________
dense_6 (Dense)                 (None, 32)           50208       concatenate[0][0]                
__________________________________________________________________________________________________
dropout_2 (Dropout)             (None, 32)           0           dense_6[0][0]                    
__________________________________________________________________________________________________
dense_7 (Dense)                 (None, 64)           2112        dropout_2[0][0]                  
__________________________________________________________________________________________________
dense_8 (Dense)                 (None, 1)            65          dense_7[0][0]                    
==================================================================================================
Total params: 52,385
Trainable params: 52,385
Non-trainable params: 0

 

 

 

 

總結:

網絡容量:與網絡可訓練參數量成正比

網絡中神經單元數越多,層數越多,神經網絡的擬合能力越強。

但是訓練難度越大,訓練速度越慢,越容易產生過擬合。

超參數:需要人為選擇,不是通過優化算法優化的參數,如,中間層的神經元個數,學習率

如何提高網絡的擬合能力?

增大網絡容量:

1、增加層,大大提高網絡的擬合能力

2、增加隱藏神經元個數,提高不是很明顯

過擬合:訓練精度很高,測試精度很低。

解決方法:

dropout,隨機丟棄神經網絡的層中的節點

1、取平均的作用:相當於相同數據訓練幾個不同的神經網絡,得到的結果取平均或多數取勝的投票策略

2、減少神經元之間復雜的共適應關系

正則化:l1,l2

增加數據集:圖像增強

減小網絡規模:減少層

欠擬合:訓練精度和測試精度都低。單層神經元個數不能太小,會造成信息瓶頸

 

構建網絡的總原則

1、增大網絡容量,直到過擬合

2、采取措施抑制過擬合

3、繼續增大網絡容量,直到過擬合

 

TensorFlow2.0構建模型方式:

1、keras.Sequential()

2、函數式:先定義層在加入到網絡中,keras.Model(inputs=[],outputs=[])

3、子類式





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM