激活函数

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 定义x轴数据范围
x = np.linspace(-10, 10, 100)

# 定义Sigmoid函数
####参考教材内容,补全关键代码,重新运行#####   
sigmoid=tf.sigmoid(x)
# 定义ReLU函数
####参考教材内容,补全关键代码,重新运行#####   
relu=tf.nn.relu(x)
# 定义Tanh函数
####参考教材内容,补全关键代码,重新运行#####   
tanh=tf.tanh(x)
# 定义Softmax函数
####参考教材内容,补全关键代码,重新运行#####   
softmax=tf.nn.softmax(x)
# 绘制函数曲线
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.plot(x, sigmoid)
plt.title('Sigmoid Function')

plt.subplot(2, 2, 2)
plt.plot(x, relu)
plt.title('ReLU Function')

plt.subplot(2, 2, 3)
plt.plot(x, tanh)
plt.title('Tanh Function')

plt.subplot(2, 2, 4)
plt.plot(x, softmax)
plt.title('Softmax Function')

# 显示图形
plt.tight_layout()
plt.show()

MLP

####参考教材内容,补全关键代码,重新运行#####   
import tensorflow as ts
print(tf.__version__)

import numpy as np
import pandas as pd
####参考教材内容,补全关键代码,重新运行#####   
import tensorflow as ts
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

# 加载数据集
#dataset_path = tf.keras.utils.get_file("auto-mpg.data", "http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")
# 效能(公里数每加仑),气缸数,排量,马力,重量
# 加速度,型号年份,产地
column_names = ['MPG','Cylinders','Displacement','Horsepower','Weight', 'Acceleration', 'Model Year', 'Origin']
data = pd.read_csv("auto-mpg.data", names=column_names, na_values = "?", comment='\t', sep=" ", skipinitialspace=True)
# 查看部分数据
####参考教材内容,补全关键代码,重新运行#####   
data.head()

print("预处理前data.shape:",data.shape)
print("数据缺失情况统计:")
print(data.isna().sum())
#清除缺失数据所在行
####参考教材内容,补全关键代码,重新运行#####   
data=data.dropna()

# 处理类别型数据,其中origin列代表了类别1,2,3,分布代表产地:美国、欧洲、日本
# 先弹出这一列
origin = data.pop('Origin')
# 根据origin列来写入新列
data['USA'] = (origin == 1)*1.0
data['Europe'] = (origin == 2)*1.0
data['Japan'] = (origin == 3)*1.0
####参考教材内容,补全关键代码,重新运行#####  
data.head()

# 提取特征和目标变量
X = data.drop('MPG', axis=1).values
y = data['MPG'].values
# 数据归一化
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
####参考教材内容,补全关键代码,重新运行#####   
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.and2,random_state=42)
print("预处理后:",X_train.shape,X_test.shape,y_train.shape,y_test.shape)

class MLP_Model(tf.keras.Model):
    def __init__(self):
        super(MLP_Model, self).__init__()
        # 创建3个全连接层
####参考教材内容,补全关键代码,重新运行##### 
        self.fc1=tf.keras.layers.Dense(64,activation='relu')
        self.fc2=tf.keras.layers.Dense(64,activation='relu')
        self.fc3=tf.keras.layers.Dense(1)
    def call(self, inputs, training=None, mask=None):
        # 依次通过3个全连接层
        x = self.fc1(inputs)
        x = self.fc2(x)
        x = self.fc3(x)
        return x
model = MLP_Model()
model.build(input_shape=(None, 9))
model.summary()
optimizer = tf.keras.optimizers.RMSprop(0.001)
train_db = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_db = train_db.shuffle(100).batch(32)

train_mae_losses = []
test_mae_losses = []
for epoch in range(200):
    for step, (x,y) in enumerate(train_db):
####参考教材内容,补全关键代码,重新运行#####  
        with tf.GradienTape() as tape:
            out=model(x)
            mae_loss=tf.reduce_mean(tf.keras.losses.MAE(y,out))
        if epoch % 10==0 and step % 5==0
            print(epoch,step,float(mae_loss))
        grads=tape.gradient(mae_loss,model.trainable_variables)
        optimizer.apply_gradient(zip(grads,model.trainable_variables))
    train_mae_losses.append(float(mae_loss))
    out = model(tf.constant(X_test))
    test_mae_losses.append(tf.reduce_mean(tf.keras.losses.MAE(y_test, out)))

import matplotlib.pyplot as plt
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('MAE')
plt.plot(train_mae_losses,  label='Train')
####参考教材内容,补全关键代码,重新运行##### 
plt.plot(test_mae_losses,label='Test')
plt.legend()
plt.show()