小编在自学机器学习过程中,参考莫烦大佬的python教程进行了keras的实例运行,在此记录一下,以免忘记。

keras在Linux的安装很简单,直接   pip install keras   一行命令就可以啦,结果如下:

因为呢我已经安装过了,所以会提示already satisfied 。另外呢keras的bankend有theano和TensorFlow,可以随意切换,其中TensorFlow只适用于Linux和mac版本,theano三个版本全部使用(包含Windows) 。

小编一直是使用TensorFlow的,如果想要切换为theano 可以去百度,网上教程很多,小编就略过了。

言归正传,这次是使用keras+tensorflow进行回归模型的实例,代码copy莫烦大佬的,具体如下:


#-*- coding: UTF-8 -*-
"""
To know more or get code samples, please visit my website:
https://morvanzhou.github.io/tutorials/
Or search: 莫烦Python
Thank you for supporting!
"""

# please note, all tutorial code are running under python3.5.
# If you use the version like python2.7, please modify the code accordingly



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

# create some data   创建散点图数据
X = np.linspace(-1, 1, 200)
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]     # first 160 data points
X_test, Y_test = X[160:], Y[160:]       # last 40 data points

# build a neural network from the 1st layer to the last layer
model = Sequential()

model.add(Dense(units=1, input_dim=1)) 

# 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('\nTesting ------------')
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()

实际运行效果如下:

首先弹出数据集结构,这是我们创建data的点集,然后plot显示

这条直线就是我们用回归模型拟合出的,效果还不错。

这是模型的相关数据,可以看到训练的cost由4不断减小为0.002,test的cost为0.003也非常小,对于模型的权重为0.49很接近0.5,bias为1.99和接近2,基本和 程序所给出的函数计算式的相关参数一致,虽然model只有一个全连接层(dense),但对于二分类效果是可以的。

 

 

 

 

参考文章:

https://github.com/MorvanZhou/tutorials/blob/master/kerasTUT/4-regressor_example.py

https://study.163.com/course/courseLearn.htm?courseId=1003340023#/learn/video?lessonId=1003802569&courseId=1003340023

Logo

更多推荐