尝试编写我的第一个 python 程序。在一个工作示例程序(脚本)中,一些数据数组是这样定义的:
x_data = np.random.rand(100).astype(np.float32)
当我随后在 Python 控制台中键入“x_data”时,它返回
>>> x_data
array([ 0.16771448, 0.55470788, 0.36438608, ..., 0.21685787,
0.14241569, 0.20485006], dtype=float32)
并且脚本有效。
现在我想改用我自己的数据集。我正在尝试这样的声明
my_data = [1,2,3,4,5]
并将 x_data 的使用替换为 my_data,但程序无法运行。我注意到当我在 Python 控制台中键入“my_data”时,它会返回
>>> my_data
[1, 2, 3, 4, 5]
缺少“array”和“dtype=float32”的部分。我猜这种差异与问题有关。
如何声明像 x_data 一样处理的数据集 my_data,以便我可以将自己的数据输入程序?
我认为这无关紧要,但这是我开始使用的完整示例脚本(有效):
import tensorflow as tf
import numpy as np
# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
# Fit the line.
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
# Learns best fit is W: [0.1], b: [0.3]
我猜你是从 Matlab 学来的?
默认情况下,Python 方括号表示法不会为您提供任何类型的数组
:它为您提供一个更简单的内置类型list
对象。 numpy
,无处不在的第三方包,是您想要用于数组的。很明显,您已经可以使用它了。
下面的第二行将您的变量从 list
转换为 numpy
数组,其数据类型与您的其他数组 x_data
相同:
my_data = [1,2,3,4,5]
my_data = np.array(my_data, dtype=np.float32)
我是一名优秀的程序员,十分优秀!