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)