gpt4 book ai didi

python - 如何在 Python 中创建数组

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:37 25 4
gpt4 key购买 nike

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

关于python - 如何在 Python 中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com