import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
tf.__version__
>>>'2.0.0'
一,tf.kears.Dense()实现线性回归(梯度下降法)
1,读取数据
data = pd.read_csv('./数据集/Income1.csv')
data[:3]
plt.scatter(data.Education, data.Income)
plt.show()
提取Education作为属性,Income作为输出
x = data.Education
y = data.Income
2,构建全连接模型(单层)
序列化建模,一般步骤为:(详细1,详细2)
1、实例化一个Sequential类
,该类是继承于Model类;
2、添加所需要的神经网络层;
3、用compile
进行编译模型;
4、用fit
训练模型;
5、用predict
预测。
新建模型
model = tf.keras.Sequential()
增加全连接层
# 添加 y = w * x + b
# tf.keras.layers.Dense(输出_shape, 输入_shape=(数据维度, 样本数))
# 输出_shape可以自选(后边会讲如何得到最优),输入_shape要看数据维度
# Dense层就是所谓的全连接神经网络层
# 第一层需要指定输入形状,以对接输入数据的形状,比如以(1, )对接(*, 1)形状的数据。
model.add(tf.keras.layers.Dense(1, input_shape=(1, )))
查看当前模型架构
# 返回当前模型内容
# Layer/层(type/类型) Output Shape/输出形状 Param #/参数
# 全连接神经网络层 (样本数,维度) 2个参数(分别为w、b)
model.summary()
>>>Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 1) 2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
_________________________________________________________________
构建优化器(后边会细说)
# 优化算法(后边会讲)
model.