Machine Learning(一) 一个神经元网络-线性函数

一个神经元的网络(线性函数)

线性函数 y = 2 * x -1

程序源代码

1
2
3
4
5
6
7
8
9
10
from tensorflow import keras
import numpy as np
#构建模型
model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])])
model.compile(optimizer='sgd',loss='mean_squared_error')
#准备训练数据
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)
#训练模型
model.fit(xs,ys,epochs=500)

训练模型过程(截取)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Epoch 1/500
1/1 [==============================] - 0s 388ms/step - loss: 3.4976
Epoch 2/500
1/1 [==============================] - 0s 3ms/step - loss: 2.9127
Epoch 3/500
1/1 [==============================] - 0s 3ms/step - loss: 2.4493
Epoch 4/500
1/1 [==============================] - 0s 3ms/step - loss: 2.0814
Epoch 5/500
1/1 [==============================] - 0s 4ms/step - loss: 1.7888
Epoch 6/500
1/1 [==============================] - 0s 4ms/step - loss: 1.5555
Epoch 7/500
1/1 [==============================] - 0s 4ms/step - loss: 1.3689
Epoch 8/500
1/1 [==============================] - 0s 4ms/step - loss: 1.2191
Epoch 9/500
1/1 [==============================] - 0s 3ms/step - loss: 1.0983
Epoch 10/500
1/1 [==============================] - 0s 4ms/step - loss: 1.0005
Epoch 11/500
1/1 [==============================] - 0s 4ms/step - loss: 0.9207
Epoch 12/500
1/1 [==============================] - 0s 2ms/step - loss: 0.8551
Epoch 13/500
1/1 [==============================] - 0s 5ms/step - loss: 0.8009

使用模型

1
2
#使用模型(输入)
print(model.predict([2021]))
1
2
#输出
[[4036.6035]]
1
2
#输入
model.predict([10.0])
1
2
#输出
array([[18.984968]], dtype=float32)