import tensorflow as tf #引入tensorflow import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # 读入数据并查看 data = pd.read_csv('./income1.csv') data
# 画散点图,查看分布情况
plt.scatter(data.Education,data.Income)
<matplotlib.collections.PathCollection at 0x257d46cc188>
# 数据赋值 x = data.Education y = data.Income
# 搭建网络 model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1,input_shape=(1,)))
model.add(tf.keras.layers.Dense(10, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.summary() #ax + b
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 1) 2 _________________________________________________________________ dense_1 (Dense) (None, 10) 20 _________________________________________________________________ dense_2 (Dense) (None, 1) 11 ================================================================= Total params: 33 Trainable params: 33 Non-trainable params: 0 _________________________________________________________________
model.compile(optimizer='adam',loss='mse') #优化器选择adam,均方差选择mse
history = model.fit(x, y, epochs=5000) #训练5000次
model.predict(x) #进行预测
WARNING:tensorflow:Keras is training/fitting/evaluating on array-like data. Keras may not be optimized for this format, so if your input data format is supported by TensorFlow I/O (https://github.com/tensorflow/io) we recommend using that to load a Dataset instead. array([[16.548624], [18.795906], [21.26792 ], [23.5152 ], [25.762476], [28.234488], [30.481771], [32.729046], [34.97633 ], [37.44834 ], [39.695625], [41.9429 ], [44.414906], [46.662193], [48.90947 ], [51.38148 ], [53.62876 ], [55.876038], [58.34806 ], [60.595325], [62.842613], [65.31462 ], [67.561905], [69.80918 ], [72.05647 ], [74.528465], [76.775764], [79.02303 ], [81.49505 ], [83.742325]], dtype=float32)
其中,使用的是顺序模型。网络总三层,第一层结点数为1的全连接层,输入数据维度为1维;第二层结点数为10的全连接层,激活函数为 ReLU;最后一层为结点数为1的全连接层,为输出层。
模型编译
model.compile(optimizer='adam',loss='mse') • 1
其中,优化器选择为 adam,损失函数为 mse(均方误差)模型训练,训练次数为5000次
history = model.fit(x, y, epochs=5000) • 1
以训练后的模型对 x 进行测试,得到以后结果
model.predict(x)
# 搭建网络 model = tf.keras.Sequential()
每一次搭建网络的第一步就是这样,这叫 顺序模型 或者 序贯模型