关于tensorflow:深度学习之回归模型简单线性模型

35次阅读

共计 1040 个字符,预计需要花费 3 分钟才能阅读完成。

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

数据集生成

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()

定义线性模型

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

model.summary()

训练模型

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()

查看模型是否拟合

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()

正文完
 0