tensorflow keras 线性回归

给一组数据点xs,ys 训练后预测另外一个x对应的y值
Keras的核心数据结构是“model”,model是一种组织网络层的方式。
Keras中主要的model是Sequential model,Sequential是一系列网络层按顺序构成的栈
dense表示全连接神经网络
units: 正整数,输出空间维度
input_shape表示输入张量的形状
损失函数使用mean_squared_error,优化器使用随机梯度下降法(sgd)
epochs训练轮数,会从初始参数开始使用sgd迭代使得loss减小
首先在anaconda里面新建一个tensorflow虚拟环境,然后可以在jupyter notebook中运行下面代码
可以修改epochs,观察训练次数对预测结果的影响

import tensorflow as tf
import numpy as np
from tensorflow import keras
# Define the training data
xs = np.array([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
# Define the neural network model
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
# Configure the learning process
model.compile(optimizer='sgd', loss='mean_squared_error')
# train data
model.fit(xs, ys, epochs=100)
# predict
print(model.predict([10.0]))
posted @ 2020-04-22 20:07  jun_phy  阅读(266)  评论(0编辑  收藏  举报