- 这里使用的是tensorflow2.0.0内置的keras
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
x_data = np.random.rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data*0.1 + 0.2 + noise
plt.scatter(x_data,y_data)
plt.show()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8c53b1149a1b930e9b4fa1e4d08cf39e.png)
model = Sequential()
model.add(Dense(units=1,input_dim=1))
model.compile(optimizer='sgd',loss='mse')
for step in range(3001):
cost = model.train_on_batch(x_data,y_data)
if step % 500 == 0:
print('cost:',cost)
W,b = model.layers[0].get_weights()
print('W:',W,'b:',b)
y_pred = model.predict(x_data)
plt.scatter(x_data,y_data)
plt.plot(x_data,y_pred,'r-',lw=3)
plt.show()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f5ed81c97ddd2677cdbc8a633959750a.png)