深度学习之回归模型-简单线性模型

数据集生成

from sklearn.model_selection import train_test_split
from sklearn import datasets
import matplotlib.pyplot as plt
from tensorflow import keras

X,y = datasets.make_regression(n_samples=10000,noise=0,random_state=8,n_informative=1,n_features=1)
plt.scatter(X,y,c='blue')
plt.show()

image

定义线性模型

model = keras.models.Sequential([
    keras.layers.Dense(1,input_shape = X_train.shape[1:])]
)

model.summary()

image

训练模型

model.compile(loss = keras.losses.mean_squared_error,optimizer=keras.optimizers.Adam(),metrics=['mse'])
history = model.fit(X,y,epochs=1000,validation_split=0.25,callbacks=[keras.callbacks.EarlyStopping(patience=3)])

画出损失历史图

# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Valid'], loc='upper left')
plt.show()

image

查看模型是否拟合

import numpy as np

weights = model.get_weights()
print(weights)
print(weights[0][0,0])
print(weights[1][0])

w1 = weights[0][0,0]
b1 = weights[1][0]
m_x = np.array([-4,3])
m_y = m_x * w1 + b1

plt.plot(m_x,m_y,color = 'red')
plt.scatter(X,y,c='blue')
plt.show()

image


小鸡
214 声望24 粉丝

1.01的365次方=37.8