【问题标题】:Python import CSV into array TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe'Python 将 CSV 导入数组 TypeError:无法根据规则“安全”将数组数据从 dtype('float64') 转换为 dtype('S32')
【发布时间】:2018-09-12 12:20:16
【问题描述】:

当我尝试从 csv 文件加载数据时,出现以下错误:

TypeError:无法根据规则“安全”将数组数据从 dtype('float64') 转换为 dtype('S32')

在我原来的代码中:

training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])

我想从 csv 文件中读取数据,而不是像这样的 training_set_inputs。我的 csv 文件包含以下相同的数据:

0,0,1
1,1,1
1,0,1
0,1,1

我像这样加载我的 csv 文件:

import csv

training_set_inputs = [] 
# open file
with open('neuron.csv', 'rb') as f:
    reader = csv.reader(f)

    # read file row by row
    for row in reader:
        training_set_inputs.append(row)

这是我的整个脚本:

import pandas as pd
import csv
from numpy import exp, array, random, dot


class NeuralNetwork():
    def __init__(self):
        # Seed the random number generator, so it generates the same numbers
        # every time the program runs.
        random.seed(1)

        # We model a single neuron, with 3 input connections and 1 output connection.
        # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1
        # and mean 0.
        self.synaptic_weights = 2 * random.random((3, 1)) - 1

    # The Sigmoid function, which describes an S shaped curve.
    # We pass the weighted sum of the inputs through this function to
    # normalise them between 0 and 1.
    def __sigmoid(self, x):
        return 1 / (1 + exp(-x))

    # The derivative of the Sigmoid function.
    # This is the gradient of the Sigmoid curve.
    # It indicates how confident we are about the existing weight.
    def __sigmoid_derivative(self, x):
        return x * (1 - x)

    # We train the neural network through a process of trial and error.
    # Adjusting the synaptic weights each time.
    def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations):
        for iteration in xrange(number_of_training_iterations):
            # Pass the training set through our neural network (a single neuron).
            output = self.think(training_set_inputs)

            # Calculate the error (The difference between the desired output
            # and the predicted output).
            error = training_set_outputs - output

            # Multiply the error by the input and again by the gradient of the Sigmoid curve.
            # This means less confident weights are adjusted more.
            # This means inputs, which are zero, do not cause changes to the weights.
            adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output))

            # Adjust the weights.
            self.synaptic_weights += adjustment

    # The neural network thinks.
    def think(self, inputs):
        # Pass inputs through our neural network (our single neuron).
        return self.__sigmoid(dot(inputs, self.synaptic_weights))


if __name__ == "__main__":

    #Intialise a single neuron neural network.
    neural_network = NeuralNetwork()

    print "Random starting synaptic weights: "
    print neural_network.synaptic_weights

    # The training set. We have 4 examples, each consisting of 3 input values
    # and 1 output value.
    #training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
    #training_set_inputs = pd.read_csv("neuron.csv", sep=',',header=None)
    training_set_inputs = []
    with open('neuron.csv', 'r') as f:
      reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
      for row in reader:
          training_set_inputs.append(row)
          training_set_outputs = array([[0, 1, 1, 0]]).T

    # Train the neural network using a training set.
    # Do it 10,000 times and make small adjustments each time.
    neural_network.train(training_set_inputs, training_set_outputs, 10000)

    print "New synaptic weights after training: "
    print neural_network.synaptic_weights

    # Test the neural network with a new situation.
    print "Considering new situation [1, 0, 0] -> ?: "
    print neural_network.think(array([1, 0, 0]))

【问题讨论】:

  • 有什么问题?
  • 你的问题是什么?
  • 这有帮助吗? - Convert to CSV to array in python
  • 您没有指定哪一行给出了错误,但可能是您的错误与 csv 读取无关。会不会是 adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output)) 行包含一些浮点值?
  • 文件“neuron.py”,第 75 行,在 神经网络.train(training_set_inputs, training_set_outputs, 10000) 文件“neuron.py”,第 34 行,在火车输出 = self.think( training_set_inputs) 文件“neuron.py”,第 51 行,in think return self.__sigmoid(dot(inputs, self.synaptic_weights)) TypeError: Cannot cast array data from dtype('float64') to dtype('S32') 根据规则“安全”

标签: python arrays csv


【解决方案1】:

尝试将“rb”参数更改为“r”。 “b”标志用于二进制文件。

>>> with open('neuron.csv', 'r') as f:
...     reader = csv.reader(f)
...     for row in reader:
...         training_set_inputs.append(row)
... 
>>> training_set_inputs
[['0', '0', '1'], ['1', '1', '1'], ['1', '0', '1'], ['0', '1', '1']]

【讨论】:

  • 实际上,我正在使用神经元网络代码。使用 csv 加载 training_set_inputs 变量不起作用。 TypeError:无法根据规则“安全”将数组数据从 dtype('float64') 转换为 dtype('S32')
  • @user979974 将此信息添加到您的问题中,否则不清楚您的问题是什么。