神经网络技术发展已经有相当长的时间了。然而,作为编程人员,很多人调用KERAS库的时候,还是束手无策。凡事,无论难易,都应当从简单的入手。这样,重复很多简单的事情,可以掌握一定的规律。根据规律就可以实现复杂事情的处理。神经网络亦是如此,此种学习方式,循序渐进的进行下去就能较好掌握tensorflow, pytorch中的keras编程。这段时间主要查阅了国外的一些文献资料。整理一下,留存于csdn网络中,以备后用。
1.直线拟合
采样数据是:
import numpy as np import os import matplotlib.pyplot as plt num_data=100 significant_figure=3 data_x=np.round(np.sort(np.random.random_sample(num_data))-0.5,significant_figure) W,B=0.9,0.3 sigma=(np.random.random_sample(num_data)-0.5)/10 data_y=W*data_x+B+sigma
keras后端环境为tensorflow
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
# y = w*x + b 设置顺序神经网络模型,一个节点输入,一个隐藏层一个节点
model=keras.Sequential(
[
keras.layers.Input(shape=(1,)),
keras.layers.Dense(1,)
]
)
model.summary()
#设置训练参数
model.compile(
loss='mse',
# optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),
# optimizer=tf.keras.optimizers.RMSprop(lr=.005),
optimizer='sgd',
metrics=['mse'],
)
#callbacks = [
# keras.callbacks.ModelCheckpoint(filepath="model_at_epoch_{epoch}.keras"),
# keras.callbacks.EarlyStopping(monitor="val_loss", patience=2),
#]
#训练并查看训练进度
model.fit(
data_x,
data_y,
batch_size=1,
epochs=30,
# validation_split=0.15,
# callbacks=callbacks,
)
#预测结果值
calc_y=model.predict(data_x)#callbacks=callbacks)
plt.plot(data_x,calc_y,'r-')
plt.plot(data_x,data_y,'bo')
plt.show()
下面的代码专门用来拟合双曲线:
from sklearn.preprocessing import PolynomialFeatures def generate_data(): X=np.arange(-30,30,1) y=9*X**3+5*X**2+np.random.randn(60)*1000 return X,y trX, trY = generate_data() trX = trX/max(trX) trY = trY/max(trY) #plot the data fig, ax = plt.subplots() ax.scatter(trX, trY) n = 3 trX_expanded = np.expand_dims(trX, axis=1)#one column array poly = PolynomialFeatures(n) # returns: [1, x, x^2, x^3]#4 columns basis function trX_expanded = poly.fit_transform(trX_expanded)#every point has 4 features model=keras.Sequential( [ keras.layers.Input((1)),#because this is array it has n+1 columns keras.layers.Dense(1) ] ) #model_linear = keras.Model(inputs=inp, outputs=out) model.compile( optimizer=tf.keras.optimizers.Adam(lr=0.05), loss='mse', metrics=['mse']) model.fit(trX, trY,batch_size=1,epochs=50,) #ax.scatter(trX, trY) ax.plot(trX, model.predict(trX), color="red") plt.show() fig, ax = plt.subplots() inp = keras.layers.Input((n+1)) #since one of the features is 1, we need an extra input out = keras.layers.Dense(1)(inp) modelp = keras.Model(inputs=inp, outputs=out) modelp.compile(optimizer=tf.keras.optimizers.Adam(lr=0.05), loss='mse',metrics=['mse']) modelp.fit(trX_expanded, trY, epochs=100) ax.scatter(trX, trY) ax.plot(trX, modelp.predict(trX_expanded), color="red") plt.show()