Regression案例—基于Keras库

"""
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

# 4 - Regressor example

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)) #第一个hidden layer: units 表示输出维度,input_dim表示输入维度

# 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()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Keras进行基本回归是pyimagesearch中一个非常有用的教程。回归是机器学习中的一个重要任务,用于预测连续性变量的值。这个教程重点介绍了如何使用Python和Keras来构建和训练一个回归模型。 首先,教程中介绍了回归问题的基本概念,并说明了为什么Keras是一个强大的工具来解决这个问题。然后,教程给出了一个具体的例子,通过建立一个简单的神经网络模型来解决汽车燃油效率预测的问题。 教程首先介绍了数据集的预处理步骤,包括导入数据、数据划分和特征归一化等。然后,教程讲解了如何使用Keras来构建一个神经网络模型。这个模型包括几个全连接层和激活函数,以及一个输出层来预测连续性目标变量。教程详细解释了每一层的作用和参数设置。 接下来,教程展示了如何使用Keras来编译和训练模型。教程中提到了损失函数、优化器和评估指标的选择,并介绍了一些常用的技巧,如早停法和学习率调度。教程还提供了一些训练时的可视化和监控方法,以便更好地理解模型的训练过程和性能。 最后,教程给出了使用训练好的模型进行预测的方法,并演示了如何计算预测结果的误差。教程强调了如何使用模型进行实际预测,并提供了一些实用的技巧和建议。 总的来说,pyimagesearch的basic regression with keras教程详细介绍了如何使用Keras来解决回归问题,并提供了实际的代码示例和建议。这个教程对于初学者来说是非常有用的,同时也对于有经验的数据科学家来说是一个很好的参考资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值