全连接神经网络TensorFlow (直接可用版)

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)

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值