python - Tensorflow实践 y = xw 如何初始化向量x?

标签 python machine-learning tensorflow

我正在学习第一次机器学习练习。

这是每月气温的预测系统。

train_t 包含温度,train_x 包含每个数据的权重。

但是我有一个问题,初始化 train_x

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

x = tf.placeholder(tf.float32,[None,5])
w = tf.Variable(tf.zeros([5,1]))

y = tf.matmul(x,w)
t = tf.placeholder(tf.float32,[None,1])

loss = tf.reduce_sum(tf.square(y-t))
train_step = tf.train.AdamOptimizer().minimize(loss)

sess = tf.Session()
sess.run(tf.initialize_all_variables())

train_t = np.array([5.2,5.7,8.6,14.9,18.2,20.4,25.5,26.4,22.8,17.5,11.1,6.6]) #montly temperature
train_t = train_t.reshape([12,1])
train_x = np.zeros([12,5])

for row, month in enumerate(range(1,13)):
    for col, n in enumerate(range(0,5)):
        train_x[row][col] = month**n ## why initialize like this??


i = 0
for _ in range(10000):
    i += 1
    sess.run(train_step,feed_dict={x:train_x,t:train_t})
    if i % 1000 == 0:
        loss_val = sess.run(loss,feed_dict={x:train_x,t:train_t})
        print('step : %d,Loss: %f' % (i,loss_val))
        w_val = sess.run(w)
        pprint(w_val)

def predict(x):
    result = 0.0
    for n in range(0,5):
        result += w_val[n][0] * x**n
    return result

fig = plt.figure()
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(1,12)
subplot.scatter(range(1,13),train_t)
linex = np.linspace(1,12,100)
liney = predict(linex)
subplot.plot(linex, liney)

不过这里我不明白

for row, month in enumerate(range(1,13)): #
    for col, n in enumerate(range(0,5)): #
        train_x[row][col] = month**n  ## why initialize like this??

这是什么意思?? 我的书里没有关于这个的评论?? 为什么要在这里初始化train_x??

最佳答案

事实上,这段代码:

train_t = np.array([5.2,5.7,8.6,14.9,18.2,20.4,25.5,26.4,22.8,17.5,11.1,6.6]) #montly temperature
train_t = train_t.reshape([12,1])
train_x = np.zeros([12,5])

for row, month in enumerate(range(1,13)):
    for col, n in enumerate(range(0,5)):
        train_x[row][col] = month**n

是你数据的生成。它初始化 train_ttrain_x ,它们是将被注入(inject)到 placeholders xt< 中的数据

train_t 是温度张量 train_x 是每个温度的权重排序张量。 它们构成了数据集。

关于python - Tensorflow实践 y = xw 如何初始化向量x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44779086/

相关文章:

machine-learning - 如何忽略日志打印caffe中未使用的层

python - scikit-learn 中 train_test_split() 的不稳定行为

python - 使用 WALS 方法在 tensorflow 2.0 中进行矩阵分解

python - Tabula 按区域坐标提取表格

python - 在 Cython 中使用 zlib 压缩 NumPy 数组

python - 使用 microsoft azure 机器学习运行 python 脚本

tensorflow - 从子流程创建引擎时 TensorRT 创建异常

python - 执行 Linux 命令并获取 PID

python - 如何将文件夹中的所有 .csv 文件转换为具有多个工作表选项卡(每个 .csv 1 个)的单个 .xlsx 文件?

python - 使用 BERT 对单词位置进行序列标记