如何在Python中创建数组

时间:2016-12-16 17:23:46

标签: python arrays python-3.x numpy

尝试编写我的第一个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]

2 个答案:

答案 0 :(得分:3)

我猜你是来自Matlab吗?

Python方括号表示法默认情况下不会为您提供任何类型的array:它为您提供了内置类型list的更简单对象。 numpy,无处不在的第三方包,是您要用于数组的。显然你已经有了它。

下面第二行将您的变量从list转换为numpy数组,其数据类型与您的其他数组x_data相同:

my_data = [1,2,3,4,5]
my_data = np.array(my_data, dtype=np.float32)

答案 1 :(得分:1)

如果您只使用np.array

,numpy将从列表中构造一个数组
import numpy as np
arr = np.array([1, 2, 3, 4])

请注意,您也可以指定数据类型:

arr_int32 = np.array([1, 2, 3, 4], dtype=np.int32)
arr_float = np.array([1, 2, 3, 4], dtype=np.float64)

另请注意,有时您可能正在使用可能是列表的对象,或者它可能是一个numpy数组。如果您将数组作为输入传递,np.array将复制数组。出于性能原因,有时不希望这样做。如果您发现自己处于这种情况,可以使用np.asarray将非数组转换为数组,但它将不会更改数组。