• keras 简单使用


    使用Keras做线性拟合

    import keras
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.models import Sequential
    from keras.layers import Dense
    
    # 使用numpy生成100个随机点
    x_data = np.random.rand(100)
    noise = np.random.normal(0, 0.02, x_data.shape)
    y_data = x_data*0.1 + 0.2 + noise
    
    # 构建模型
    model = Sequential()
    model.add(Dense(1, input_dim=1))
    model.compile(optimizer='sgd', loss='mse')
    
    # 训练模型
    for step in range(3001):
        cost = model.train_on_batch(x_data, y_data)
        if step % 500 == 0:
            print('cost:', cost)
    
    # 打印出权值和偏置值
    w, b = model.layers[0].get_weights()
    print('W:', w, 'B: ', b)

    非线性拟合

    import keras
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.models import Sequential
    from keras.layers import Dense
    from keras.optimizers import SGD
    
    # 生成一批数据
    x_data = np.linspace(-0.5, 0.5, 200)
    noise = np.random.normal(0, 0.02, x_data.shape)
    y_data = np.square(x_data) + noise
    
    # 构建模型
    model = Sequential()
    model.add(Dense(10, input_dim=1, activation='tanh'))
    model.add(Dense(1))
    sgd = SGD(lr=0.1)
    model.compile(optimizer=sgd, loss='mse')
    
    # 训练模型
    for step in range(3001):
        cost = model.train_on_batch(x_data, y_data)
        if step % 500 == 0:
            print('cost:', cost)
    
    # 打印出权值和偏置值
    w, b = model.layers[0].get_weights()
    print('W:', w, 'B: ', b)

    手写数字识别

    import keras
    from keras.datasets import mnist
    from keras.utils import  np_utils
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.models import Sequential
    from keras.layers import Dense
    
    # 载入数据
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    # 转换数据格式
    x_train = x_train.reshape(x_train.shape[0], -1)
    x_test = x_test.reshape(x_test.shape[0], -1)
    y_train = np_utils.to_categorical(y_train, num_classes=10)
    y_test = np_utils.to_categorical(y_test, num_classes=10)
    
    # 创建模型
    model = Sequential()
    model.add(Dense(64, input_dim=784, bias_initializer='one', activation='sigmoid'))
    model.add(Dense(10, bias_initializer='one', activation='softmax'))
    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
    model.fit(x_train, y_train, batch_size=128, epochs=10)
    
    loss, accurancy = model.evaluate(x_test, y_test)
    print('loss: ', loss)
    print('accurancy: ', accurancy)
  • 相关阅读:
    使用DataList进行ItemDataBound时出来重复绑定
    往一个数据添加另外一个数据表里面的数据
    在ServU配置ODBC过程记录(一)
    在RowDeleting中GridViewDeleteEventArgs e的RowIndex获得值错误的问题
    在Master母版页中通过FindControl()方法获取服务器控件
    经典的间隔时间滚动新闻(图片),可控制滚动
    为枚举类型添加描述信息 this 扩展 泛型约束 位运算[转]
    SQL Server 获取插入记录后的ID(自动编号)
    Shapes
    CSSFriendlyAdapter 的一个Bug
  • 原文地址:https://www.cnblogs.com/abc23/p/12299607.html
Copyright © 2020-2023  润新知