• 用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)

    输出结果

     

  • 相关阅读:
    【操作系统】 管程机制
    【Java】 大话数据结构(13) 查找算法(4) (散列表(哈希表))
    【操作系统】 信号量机制
    【Java】 奇偶数的判断
    【Java】 大话数据结构(12) 查找算法(3) (平衡二叉树(AVL树))
    MySQL之库操作
    数据库简介
    MySQL的知识海洋
    python并发编程之多进程(理论)
    python并发编程之多进程(实现)
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9600793.html
Copyright © 2020-2023  润新知