keras实现简单的全连接神经网络

导入库:

import numpy as np
from keras.models import Sequential 
from keras.layers import Dense
import matplotlib.pyplot as plt

产生数据和数据分割

X=np.linspace(-1,1,300)#产生-1到1等距离的300个数
np.random.shuffle(X)#随机打乱
Y=2*X+5+np.random.normal(0,0.1,300)#函数,并增加正态分布的噪声
x_train=X[:200]
y_train=Y[:200]
x_test,y_test=X[200:],Y[200:]

搭建网络

model=Sequential()
model.add(Dense(output_dim=1,input_dim=1))#全连接层,output_dim输入个数 input_dim输出个数
#model.add(Dense(units=1,input_dim=1))
#model.add(Dense(units=1,input_dim=1))
model.compile(loss='mse',optimizer='sgd')

训练

print('Training---------')
for step in range(300):#迭代300次
    cost=model.train_on_batch(x_train,y_train)#利用model.train_on_batch训练,输出损失
    if step % 50 == 0:
        print(cost)

测试

print('\nTesting---------')
cost=model.evaluate(x_test,y_test,batch_size=10)#测试
print('Test cost:',cost)
W0,b0=model.layers[0].get_weights()#输出参数
#W1,b1=model.layers[1].get_weights()
#w2,b2=model.layers[2].get_weights()
print('Weight=',W0,'\nbiases=',b0)
y_pred=model.predict(x_test) #输出预测值
#print(y_pred)
plt.scatter(X_test, Y_test)#绘图
plt.plot(X_test, Y_pred)

保存模型,删除模型,导入模型

model.save('my_model.h5')   # HDF5 file,保存模型HDFS格式
del model  # 删除模型
# load
model = load_model('my_model.h5')

print('test before save: ', model.predict(X_test[0:2]))
model.save('my_model.h5')   # HDF5 file, you have to pip3 install h5py if don't have it
del model  # deletes the existing model

# load
model = load_model('my_model.h5')
print('test after load: ', model.predict(X_test[0:2]))
"""
# save and load weights
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')

# save and load fresh network without trained weights
from keras.models import model_from_json
json_string = model.to_json()
model = model_from_json(json_string)
"""

 

你可能感兴趣的:(深度学习)