2016-12-16 76 views
0

試圖編寫我的第一個python程序。在一個工作示例程序(腳本)中,數據的某些陣列的定義如下:如何在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] 

並將my_data替換爲x_data,但程序無法正常工作。我注意到,當我在Python控制檯鍵入「my_data」,則它返回

>>> my_data 
    [1, 2, 3, 4, 5] 

其缺少說「陣列」和「D類= FLOAT32」部分。我猜測這種差異與問題有關。

如何聲明一個數據集my_data,該數據集將被視爲x_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] 

回答

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

我一直避免Matlab和Python的。我在C++上長大。感謝您的快速幫助! –

1

numpy的將修建從列表中的數組,如果你只是用np.array

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將非數組轉換爲數組,但它會返回數組。