线性回归模型
这里注意 tensorflow2.0默认代的不是完整版 keras
pip install keras -U --pre
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
print(tf.__version__)
from keras.models import Sequential
from keras.layers import Dense
X=np.linspace(-1,1,200)
np.random.shuffle(X) # 将数据集随机化
Y=0.5*X+2+np.random.normal(0,0.05,(200,))# 假设我们真实模型为:Y=0.5X+2
plt.scatter(X,Y)
plt.show()
X_train,Y_train=X[:160],Y[:160]
X_test,Y_test=X[160:],Y[160:]
model=Sequential()# Keras有两种类型的模型,序贯模型(Sequential)和函数式模型
# 比较常用的是Sequential,它是单输入单输出的
model.add(Dense(input_dim=1, units=1))# 通过add()方法一层层添加模型
# Dense是全连接层,第一层需要定义输入,
# 第二层无需指定输入,一般第二层把第一层的输出作为输入
# 定义完模型就需要训练了,不过训练之前我们需要指定一些训练参数
# 通过compile()方法选择损失函数和优化器
# 这里我们用均方误差作为损失函数,随机梯度下降作为优化方法
model.compile(loss='mse',optimizer='sgd')
print("training...")
for step in range(301):
cost=model.train_on_batch(X_train,Y_train)
print('traincost',cost)
training... traincost 4.216369 traincost 4.0576506 traincost 3.905112 traincost 3.7585092 traincost 3.6176078 traincost 3.482185 traincost 3.352024 traincost 3.226918 traincost 3.1066682 traincost 2.9910836 trai