遷移學習實戰

簡介

實現 二次函數的擬合,然後將新的二次函數進行遷移擬合

code

import numpy as np
import matplotlib.pyplot as plt
def fix_seed(seed=1):
    # reproducible
    np.random.seed(seed)
    
# make up data建立數據
fix_seed(1)
x_data = np.linspace(-5, 5, 100)[:, np.newaxis]  #水平軸-7~10
print(x_data)
#np.random.shuffle(x_data)
noise = np.random.normal(0, 0.1, x_data.shape)
y_data = np.square(x_data) - 5 + noise
print(y_data)


# X = np.sort(x_data,axis=0)
# y = np.sort(y_data,axis=0)

#維度轉換
print(x_data.shape,y_data.shape)
X = x_data.reshape(-1,1)
print(X.shape,y_data.shape)
print(X)


# plot input data
plt.scatter(X , y_data)  #將數據繪製圖一元二次函數的數據集點
plt.title('')
plt.show()


#建立模型
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model1 = Sequential()
model1.add(Dense(units=50,input_dim=1,activation="relu"))
model1.add(Dense(units=50,activation="relu"))
model1.add(Dense(units=1,activation="linear"))
model1.compile(optimizer="adam",loss="mean_squared_error")  
model1.summary()

#訓練模型
model1.fit(X,y_data,epochs=20000)

#預測
y_predict = model1.predict(X)
print(y_predict)


#每訓練100次 畫一次圖
fig2 = plt.figure(figsize=(7,5))
plt.scatter(X, y_data)
plt.plot(X,y_predict,'g')
plt.title('y-x 100 predict')
plt.xlabel("x")
plt.ylabel("y")
plt.show()

# 保存模型
#from sklearn.externals import joblib
# import joblib
#joblib.dump(model1,'model.pkl')
model1.save("my_model")
model1.save_weights("weights.h5")

#from tensorflow import keras
#my_model = keras.models.load_model('my_model')
#my_model.load_weights("weights.h5")

from tensorflow import keras
my_model = keras.models.load_model('my_model')
my_model.load_weights("weights.h5")


#加載新數據
#生成二次函數點
def fix_seed(seed=1):
    # reproducible
    np.random.seed(seed)
 
fix_seed(1)
X2 = np.linspace(-6, 6, 120)[:, np.newaxis]+[2]  #水平軸 + 偏移
print(X2)
#np.random.shuffle(x_data)
noise = np.random.normal(1, 0.5, X2.shape)
y_data2 = np.square(X2) - 10 + noise
print(y_data2)

# plot input data
plt.scatter(X2 , y_data2)  #將數據繪製圖一元二次函數的數據集點
plt.title('')
plt.show()


#預測
y2_predict= my_model.predict(X2)


fig3 = plt.figure(figsize=(7,5))
plt.plot(X2,y2_predict,'r')
plt.scatter(X,y_data,label="data1")
plt.scatter(X2, y_data2,label="data2")
plt.title('model predict')
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()

my_model.fit(X2,y_data2,epochs=100)

#再預測
y2_predict2 = my_model.predict(X2)

fig4 = plt.figure(figsize=(7,5))
plt.plot(X2,y2_predict2,'r')
plt.scatter(X,y_data,label="data1")
plt.scatter(X2, y_data2,label="data2")
plt.title('model predict epochs = 10')
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()

image

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