前言
借助最简单的拟合函数给大家示范一下tensorflow2.0 的完整结构
拟合函数
y=ax^2+bx+c
代码
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers,optimizers,losses
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.python.keras import backend as K
from tensorflow.keras.utils import plot_model
from IPython.display import Image
import cv2
import PIL
import json, os
import sys
import labelme
import labelme.utils as utils
import glob
import itertools
class Net():#定义类
def __init__(self,savePath,mode):
self.savePath=savePath
self.mode=mode#决定训练模式
def net(self,input):#建立网络层
x=layers.Dense(100,activation='relu')(input)
x = layers.Dense(100, activation='relu')(x)
x = layers.Dense(100, activation='relu')(x)
x = layers.Dense(100, activation='relu')(x)
x=layers.Dense(1)(x)
return x
def fun(self,x):#定义标签生成的规律
a=1
b=2
c=3
y=a*x*x+b*x+c
return y
def build_mode(self):#建立模型的方法
x=keras.Input(shape=1)
y=self.net(x)
model=keras.Model(inputs=x,outputs=y)
return model
def train(self):#训练的方法
if (self.mode==0):#从头开始
model=self.build_mode()
if (self.mode==1):#继续训练
model=keras.models.load_model(self.savePath)
model.summary()
model.compile(
optimizer=keras.optimizers.Adam(1e-4,1e-5),
loss='mse' # 构造损失函数
)
train_x = []
train_y = []
for i in range(200000):#生成数据
x = np.random.uniform(-100, 100)
y = self.fun(x)
train_x.append(x)
train_y.append(y)
train_x = np.array(train_x)
train_y = np.array(train_y)
print(train_x.shape)
model.fit(train_x, train_y, batch_size=1000, epochs=200, verbose=1)#填入数据
model.save(self.savePath)#保存数据
def pred(self,x):#利用模型预测的函数
model=keras.models.load_model(self.savePath)
model.summary()
vector=[]
vector.append(x)
print(model.predict(vector))
net=Net(
savePath=r'C:\Users\Administrator\Desktop\example.h5',
mode=0
)
net.train()
另一种写法
这种写法收敛比较久,因为确实是使用大数据来求的,适用于大数据
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers,optimizers,losses
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.python.keras import backend as K
from tensorflow.keras.utils import plot_model
from IPython.display import Image
import cv2
import PIL
import json, os
import sys
import labelme
import labelme.utils as utils
import glob
import itertools
class Net():#定义类
def __init__(self):
self.savePath=r'C:\Users\Administrator\Desktop\example.h5'
self.mode=0#决定训练模式
self.batch_size=1000
self.epochs=500
def net(self,input):#建立网络层
x=layers.Dense(100,activation='relu')(input)
x = layers.Dense(200, activation='relu')(x)
x = layers.Dense(400, activation='relu')(x)
x = layers.Dense(800, activation='relu')(x)
x=layers.Dense(1)(x)
return x
def fun(self,x):#定义标签生成的规律
a=1
b=2
c=3
y=a*x*x+b*x+c
return y
def build_mode(self):#建立模型的方法
x=keras.Input(shape=1)
y=self.net(x)
model=keras.Model(inputs=x,outputs=y)
return model
def data_generator(self):
while True:
train_x = []
train_y = []
for i in range(self.batch_size): # 生成数据
x = np.random.uniform(-100, 100)
y = self.fun(x)
train_x.append(x)
train_y.append(y)
train_x = np.array(train_x)
train_y = np.array(train_y)
yield train_x,train_y
def train(self):#训练的方法
if (self.mode==0):#从头开始
model=self.build_mode()
if (self.mode==1):#继续训练
model=keras.models.load_model(self.savePath)
model.summary()
model.compile(
optimizer=keras.optimizers.Adam(1e-4,1e-5),
loss='mse' # 构造损失函数
)
checkpoint = keras.callbacks.ModelCheckpoint(self.savePath, monitor='val_loss', verbose=1,
save_best_only=True, mode='min')#设置存储点的规则
callbacks = [checkpoint]
train=self.data_generator()
test =self.data_generator()
model.fit_generator(train,steps_per_epoch=1000,validation_data=test,validation_steps=100,epochs=self.epochs,callbacks=callbacks)#填入数据
model.save(self.savePath)#保存数据
def pred(self,x):#利用模型预测的函数
model=keras.models.load_model(self.savePath)
model.summary()
vector=[]
vector.append(x)
print(model.predict(vector))
net=Net()
net.train()