【tensorflow】1.拟合曲线

写demo的时候,遇到一个问题,排查了很久也找不到原因。
若生成训练数据的时候,用这种方式生成

num_points = 1000
x = np.linspace(0,10,num_points )
y = a * x * x + b * x + c

则在求loss的时候,loss越来越大,至至NAN,排查半天发现,这里linspace参数必须(0,1),也就是x必须0-1之间,才能正常求出loss,不知道为什么?

# -*- coding: utf-8 -*-
# @File    : 2_LinearRegression.py
# @Time    : 2018/5/18 16:59
# @Author  : hyfine
# @Contact : foreverfruit@126.com
# @Desc    : tensorflow实现的线性回归——二次曲线

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

# ------数据准备-------------------
# 生成1000个数据对作为训练集
num_points = 1000
vectors_set = []
for i in range(num_points):
    x1 = np.random.normal(0.0, 0.55)
    y1 = 0.9 * x1 * x1 + 0.6 * x1 + 0.2 + np.random.normal(0.0, 0.03)
    vectors_set.append([x1, y1])

x = np.array([v[0] for v in vectors_set])
y = np.array([v[1] for v in vectors_set])

# ----------训练------------------
# 生成参数
A = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
B = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
C = tf.Variable(tf.zeros([1]))

y_ = A * x * x + B * x + C
# 定义loss
loss = tf.reduce_mean(tf.square(y - y_))
# 梯度下降法优化参数(学习率为lr)
lr = 0.1
optimizer = tf.train.GradientDescentOptimizer(lr)
# 训练的过程就是最小化这个误差值
train = optimizer.minimize(loss)

# 通过session执行上述操作
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)

# 初始化 A B C
print('A=', sess.run(A), ' B=', sess.run(B), ' C=', sess.run(C), ' loss=', sess.run(loss))

# 执行训练,根据loss阈值退出迭代
step = 0
while (sess.run(loss) > 1e-3):
    step += 1
    sess.run(train)
    # 输出训练好的ABC
    print('step=', step, ' A=', sess.run(A), ' B=', sess.run(B), ' C=', sess.run(C), ' loss=', sess.run(loss))

# 原图
plt.scatter(x, y, c='r')
x = np.linspace(x.min(),x.max(),100)
temp = sess.run(A) * x * x + sess.run(B) * x + sess.run(C)
# 拟合曲线
plt.plot(x, temp, c='g')
plt.show()

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于TensorFlow的欠拟合和过拟合的Python示例: 首先,我们需要导入必要的库和数据集: ```python import tensorflow as tf from tensorflow import keras import numpy as np # 加载数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.boston_housing.load_data(seed=42) ``` 接下来,我们需要对数据进行预处理: ```python # 标准化数据 mean = x_train.mean(axis=0) std = x_train.std(axis=0) x_train = (x_train - mean) / std x_test = (x_test - mean) / std ``` 然后,我们可以定义一个函数来构建模型: ```python def build_model(): model = keras.Sequential([ keras.layers.Dense(64, activation='relu', input_shape=(x_train.shape[1],)), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(1) ]) optimizer = tf.keras.optimizers.RMSprop(0.001) model.compile(loss='mse', optimizer=optimizer, metrics=['mae']) return model ``` 接下来,我们可以训练模型并绘制训练和验证的损失曲线: ```python # 构建模型 model = build_model() # 训练模型 history = model.fit(x_train, y_train, epochs=500, validation_split=0.2, verbose=0) # 绘制训练和验证的损失曲线 import matplotlib.pyplot as plt def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Abs Error [$1000]') plt.plot(history.epoch, np.array(history.history['mae']), label='Train Loss') plt.plot(history.epoch, np.array(history.history['val_mae']), label = 'Val loss') plt.legend() plt.ylim([0,5]) plt.show() plot_history(history) ``` 最后,我们可以使用测试集评估模型的性能: ```python # 使用测试集评估模型的性能 test_loss, test_mae = model.evaluate(x_test, y_test, verbose=0) print('Test MAE: ${:,.2f}'.format(test_mae * 1000)) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值