我的深度学习之helloworld小程序

来源:互联网 发布:php 去除双引号 编辑:程序博客网 时间:2024/05/28 17:06
# -*- coding:utf-8 -*-


import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt 


#create some data
X = np.linspace(-1,1,200)    #在-1和1之间等分200份
np.random.shuffle(X)         #将X打乱顺序
Y = 0.5 * X + 2 + np.random.normal(0,0.05,(200,))  #normal正态分布随机数


#plot data
plt.scatter(X,Y)
plt.show()


X_train,Y_train = X[:160],Y[:160]   #前160个数当作训练数据
X_test,Y_test = X[160:],Y[160:]     #后40个当测试数据


#build a nerual network from the 1st layer to the last layer
model = Sequential()
model.add(Dense(output_dim=1,input_dim = 1))   #X和Y都只有一维
# model.add(Dense(output_dim=1))   #add()默认输入是上一层的输出


#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)   #手动的一个个将数据送入网络中训练


if step % 100 == 0:
print('train cost:',cost)




#test
print('\nTest--------')
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)






#plotting the prediction
Y_pred = model.predict(X_test)
plt.scatter(X_test,Y_test)
plt.plot(X_test,Y_pred)
plt.show()









一开始少加了个右括号,一直跑不出结果。。。

还是开心!

继续加油!




































原创粉丝点击