Skip to article frontmatterSkip to article content

Kaggle

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# Create an 8x1x8 neural network
model = Sequential([
    Dense(1, activation='relu', input_shape=(8,)),  # Hidden layer: 1 neurons, input: 8 features
    Dense(8, activation='sigmoid')                  # Output layer: 8 neurons
])

# Compile the model
model.compile(optimizer='adam',
              loss='mse',
              metrics=['accuracy'])

# Display the model summary
model.summary()
Loading...
import numpy as np

# 创建训练数据 - 每个输入是一个8维的one-hot向量
X_train = np.array([
    [1, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 1]
])

# 输出数据与输入相同(恒等函数)
y_train = X_train.copy()

# 训练模型
history = model.fit(X_train, y_train, epochs=5000, verbose=0)

# 评估模型性能
loss, accuracy = model.evaluate(X_train, y_train, verbose=0)
print(f"最终损失:{loss:.4f}, 准确率:{accuracy:.4f}")

# 测试模型
predictions = model.predict(X_train)
print("\n预测结果:")
for i in range(len(X_train)):
    print(f"输入:{X_train[i]} -> 预测输出:{predictions[i]},期望: {y_train[i]}")
    print("-" * 50)
最终损失:0.0865, 准确率:0.5000
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 49ms/step

预测结果:
输入:[1 0 0 0 0 0 0 0] -> 预测输出:[0.16977194 0.15852644 0.1423295  0.13313144 0.15708846 0.13539074
 0.08681845 0.14484608],期望: [1 0 0 0 0 0 0 0]
--------------------------------------------------
输入:[0 1 0 0 0 0 0 0] -> 预测输出:[0.12799473 0.14991032 0.14005159 0.04417582 0.14343104 0.04631425
 0.122226   0.14165165],期望: [0 1 0 0 0 0 0 0]
--------------------------------------------------
输入:[0 0 1 0 0 0 0 0] -> 预测输出:[0.10745579 0.14494662 0.13870463 0.02204891 0.13574901 0.02355206
 0.14887916 0.1397704 ],期望: [0 0 1 0 0 0 0 0]
--------------------------------------------------
输入:[0 0 0 1 0 0 0 0] -> 预测输出:[0.24807288 0.1716589  0.14567003 0.4647702  0.17863105 0.45881805
 0.05197455 0.14955972],期望: [0 0 0 1 0 0 0 0]
--------------------------------------------------
输入:[0 0 0 0 1 0 0 0] -> 预测输出:[0.13599843 0.15169345 0.14052913 0.05618273 0.14622454 0.05851643
 0.11385675 0.1423199 ],期望: [0 0 0 0 1 0 0 0]
--------------------------------------------------
输入:[0 0 0 0 0 1 0 0] -> 预测输出:[0.24758966 0.17158546 0.14565174 0.4624356  0.17850831 0.4565462
 0.05212174 0.14953384],期望: [0 0 0 0 0 1 0 0]
--------------------------------------------------
输入:[0 0 0 0 0 0 1 0] -> 预测输出:[4.9653538e-03 8.2478210e-02 1.1852693e-01 2.2181970e-07 5.3220831e-02
 3.1674389e-07 8.7216818e-01 1.1233538e-01],期望: [0 0 0 0 0 0 1 0]
--------------------------------------------------
输入:[0 0 0 0 0 0 0 1] -> 预测输出:[0.11053896 0.1457325  0.13891967 0.02466951 0.13695587 0.02627275
 0.14430813 0.14007035],期望: [0 0 0 0 0 0 0 1]
--------------------------------------------------