zoukankan      html  css  js  c++  java
  • 用Keras搭建神经网络 简单模版(一)——Regressor 回归

    首先需要下载Keras,可以看到我用的是TensorFlow 的backend

    自己构建虚拟数据,x是-1到1之间的数,y为0.5*x+2,可视化出来

    # -*- coding: utf-8 -*-
    import numpy as np
    np.random.seed(1337) #for reproducibility再现性
    from keras.models import Sequential#按层
    from keras.layers import Dense#全连接层
    import matplotlib.pyplot as plt
    
    #creat some data
    X = np.linspace(-1,1,200) #200个x,-1到1之间
    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)
    plt.show

     

    X_train,Y_train= X[:160],Y[:160]#160个
    X_test,Y_test = X[160:], Y[160:]#40个

     

    接下来搭建1层神经网络

    #build a neural network from the 1st layer to the the last layer
    model = Sequential()
    model.add(Dense(output_dim=1,input_dim=1))#加一层
    
    #choose loss function and optimizing method
    #mse方差
    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('
    Testing~~~~~~~~')
    cost = model.evaluate(X_test,Y_test,batch_size=40)
    print('test cost:',cost)
    W,b = model.layers[0].get_weights()
    print('Weights=',W,'
    biases=',b)
    
    #plotting the prediction
    Y_pred =model.predict(X_test)
    plt.scatter(X_test,Y_test)
    plt.plot(X_test,Y_pred)

    输出结果

     

  • 相关阅读:
    将vs2010换成vs2012的主题
    写了个油猴脚本
    Myeclipse10下的access数据库配置
    点击按钮触发声音(xaml实现)
    自定义的可拖动窗体
    在博客添加时钟
    定时器写的闪光字
    C语言I博客作业02
    c语言|博客作业02
    关于软件工程的一些疑问
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9600793.html
Copyright © 2011-2022 走看看