keras回归(二)

import numpy as np
np.random.seed(1337)  # for reproducibility
#seed( ) 用于指定随机数生成时所用算法开始的整数值,如果使用相同的seed( )值,
# 则每次生成的随即数都相同,如果不设置这个值,则系统根据时间来自己选择这个值,
# 此时每次生成的随机数因时间差异而不同。
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt # 可视化模块

# create some data
X = np.linspace(-1, 1, 200)
#在指定的间隔内返回均匀间隔的数字。
#返回num均匀分布的样本,在[start, stop]。
#这个区间的端点可以任意的被排除在外。
#num=200 200个
np.random.shuffle(X)    # randomize the data
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
# plot data
plt.scatter(X, Y)
#matplotlib  画散点图
plt.show()

X_train, Y_train = X[:160], Y[:160]     # train 前 160 data points
X_test, Y_test = X[160:], Y[160:]       # test 后 40 data points

model = Sequential()
model.add(Dense(output_dim=1, input_dim=1))

# choose loss function and optimizing method
model.compile(loss='mse', optimizer='sgd')
#选择误差计算方式  和优化器

# training
print('Training -----------')
for step in range(301):
    cost = model.train_on_batch(X_train, Y_train)  #默认返回误差losse  训练
    if step % 100 == 0:
        print('train cost: ', cost)

"""
Training -----------
train cost:  4.111329555511475
train cost:  0.08777070790529251
train cost:  0.007415373809635639
train cost:  0.003544030711054802
"""

# test
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40) #评价函数 测试
print('test cost:', cost)
W, b = model.layers[0].get_weights()  #输出第一个层
print('Weights=', W, '\nbiases=', b)

"""
Testing ------------
40/40 [==============================] - 0s
test cost: 0.004269329831
Weights= [[ 0.54246825]] 
biases= [ 2.00056005]
"""
# plotting the prediction
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))

猜你喜欢

转载自blog.csdn.net/qq_39622065/article/details/81228581