Tensorflow2.0实践之基础线性回归

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets

#生成数据
data = []
for i in range(100):
    x = np.random.uniform(-10, 10)
    eps = np.random.normal(0, 0.01) * 50
    y = 1.5 * x + 1.1 + eps
    data.append([x, y])
data = np.array(data)
input_x = data[:, 0]
input_y = data[:, 1]
print(input_x)
print(input_y)
plt.scatter(input_x, input_y)
plt.show()

#创建模型

model = keras.Sequential([
        layers.Dense(1, input_dim=1) # 所完成的事情就是y=ax+b
])

model.summary()

#编译模型

model.compile(optimizers='adam',
                  loss='mse'
             )


#训练模型
model.fit(input_x, input_y, epochs=1000)

#获取训练模型的参数
weights = np.array(model.get_weights())
print(weights)

#进行结果的对比
plt.scatter(input_x, input_y)
plt.plot(input_x, model.predict(input_x), c='r') #model.predict是用训练好的模型进行预测
plt.show()

训练的参数结果如下:

w=[1.5058561563491821]
b=[1.054931879043579]

数据分布如下:

Tensorflow2.0实践之基础线性回归_第1张图片

Tensorflow2.0实践之基础线性回归_第2张图片

 

你可能感兴趣的:(线性回归)