import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
# 生成一些样例数据
np.random.seed(0)
X_train = np.random.rand(1000, 3) # 多维特征数据
y_train = 2 * X_train[:, 0] + 3 * X_train[:, 1] - 5 * X_train[:, 2] + 2 + 0.1 * np.random.randn(1000) # 线性关系的标签数据
# 创建 Sequential 模型
model = Sequential()
# 添加输入层(3 个神经元)
model.add(Dense(5, input_dim=3, activation='relu')) # 隐藏层1
model.add(Dense(3, activation='relu')) # 隐藏层2
model.add(Dense(1, activation='linear')) # 输出层
# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 查看模型结构
model.summary()
# 训练模型
history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.2, verbose=0)
# 绘制训练过程的曲线
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 预测新数据
X_new = np.array([[0.2, 0.3, 0.4], [0.5, 0.6, 0.7], [0.8, 0.9, 1.0]])
predictions = model.predict(X_new)
print("Predictions:")
print(predictions)
全连接神经网络TensorFlow (直接可用版)
于 2024-02-02 16:44:59 首次发布