AttributeError:“ NoneType”对象没有属性“ dtype” [英] AttributeError: 'NoneType' object has no attribute 'dtype'

查看:1882
本文介绍了AttributeError:“ NoneType”对象没有属性“ dtype”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用张量流实现一个简单的神经网络。这是一个二进制分类问题。 X_train:(batch_size,70)和Y_train:(batch_size,2)的形状。我正在使用csv读取数据。这是我的代码。我在python 3.6.0上运行它。

I'm trying to implement a simple neural network using tensorflow. It is a binary classification problem. Shapes of X_train: (batch_size, 70) and Y_train: (batch_size, 2). I'm reading the data using csv. Here is my code. I'm running this on python 3.6.0.

import numpy as np
import csv
import tensorflow as tf

with open('criminal_train.csv') as fp:
    reader = csv.reader(fp, delimiter=',', quotechar='"')
    train_data = np.array([row for row in reader])
    data_X = train_data[1:, 1:-1]
    data_Y = train_data[1:, -1:]

with open('criminal_test.csv') as fp:
    reader = csv.reader(fp, delimiter=',', quotechar='"')
    test_data = np.array([row for row in reader])
    predict_data = test_data[1:, 1:]

#Spltting the training data in 80:20
split = int(data_X.shape[0]*0.8)
X_train = data_X[:split, :]
X_test = data_X[split:, :]
Y_train_labels = data_Y[:split, :]
Y_test_labels = data_Y[split:, :]

#convert labels to one_hot matrices (classes=2)
Y_train = np.zeros((Y_train_labels.shape[0], 2))
Y_train[np.arange(Y_train_labels.shape[0]), Y_train_labels.astype(int)] = 1
Y_test = np.zeros((Y_test_labels.shape[0], 2))
Y_test[np.arange(Y_test_labels.shape[0]), Y_test_labels.astype(int)] = 1


def random_mini_batches(X, Y, mini_batch_size):
    m = X.shape[0]
    perm = np.random.permutation(X)
    X = X[perm, :]
    Y = Y[perm, :]
    num_batches = int(m / mini_batch_size) + 1
    bathces = []
    for k in range(num_batches):
        X_batch = X[k*mini_batch_size:(k+1)*mini_batch_size, :]
        Y_batch = Y[k*mini_batch_size:(k+1)*mini_batch_size, :]
        batches.append((X_batch, Y_batch))
    return batches

def create_placeholders():
    X = tf.placeholder(tf.float32, shape=[None,70], name='X')
    Y = tf.placeholder(tf.float32, shape=[None,2], name='Y')
    return X, Y

def forward_propagation(X):
    A1 = tf.contrib.layers.fully_connected(X, 100)
    A2 = tf.contrib.layers.fully_connected(A1, 150)
    A3 = tf.contrib.layers.fully_connected(A2, 100)
    Z5 = tf.contrib.layers.fully_connected(A3, 2, activation_fn=None)
    return Z5

def compute_cost(Z5, Y):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z5, labels=Y))

def model(X_train, X_test, Y_train, Y_test, learning_rate=0.3, beta1=0.9, beta2=0.999, mini_batch_size=32, epochs=1500):
    X, Y = create_placeholders()
    Z5 = forward_propagation(X)
    cost = compute_cost(Z5, Y)
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1, beta2=beta2).minimize(cost)
    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for epoch in range(1,epochs+1):
            batches = random_mini_batches(X_train, Y_train, mini_batch_size)
            epoch_cost = 0
            for (X_batch, Y_batch) in batches:
                _, cost = sess.run([optimizer,cost], feed_dict={X:X_batch, Y:Y_batch})
                epoch_cost += cost
            if epoch%100 == 0:
                print('Cost in epoch '+str(epoch)+' is '+str(epoch_cost))
        correct_prediction = tf.equal(tf.argmax(Z5), tf.argmax(Y))
        accuracy = tf.reducce_mean(correct_prediction, 'float')

        print('Train Accuray '+str(accuracy.eval(feed_dict={X:X_train, Y:Y_train})))
        print('Test Accuray '+str(accuracy.eval(feed_dict={X:X_test, Y:Y_test})))

model(X_train, X_test, Y_train, Y_test)

但这是我不断遇到的错误。

But this is the error that I keep getting.

Traceback (most recent call last):
  File "C:\Users\Purusharth\Desktop\hackerearth_project.py", line 90, in <module>
    model(X_train, X_test, Y_train, Y_test)
  File "C:\Users\Purusharth\Desktop\hackerearth_project.py", line 71, in model
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1, beta2=beta2).minimize(cost)
  File "C:\Python36\lib\site-packages\tensorflow\python\training\optimizer.py", line 343, in minimize
    grad_loss=grad_loss)
  File "C:\Python36\lib\site-packages\tensorflow\python\training\optimizer.py", line 394, in compute_gradients
    self._assert_valid_dtypes([loss])
  File "C:\Python36\lib\site-packages\tensorflow\python\training\optimizer.py", line 543, in _assert_valid_dtypes
    dtype = t.dtype.base_dtype
AttributeError: 'NoneType' object has no attribute 'dtype'


推荐答案

您的 compute_cost()函数返回,因为它没有 return 语句:

Your compute_cost() function returns None because it has no return statement:

def compute_cost(Z5, Y):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z5, labels=Y))

您可以使用此功能设置成本值:

You use this function to set the cost value:

cost = compute_cost(Z5, Y)

所以 cost 在此处为 None ,您将其传递给 .minimize()方法

So cost is None here, which you pass into the .minimize() method.

解决方法是使用 return ;大概您想返回 tf.reduce_mean()结果:

The fix is to use return; presumably you wanted to return the tf.reduce_mean() result:

def compute_cost(Z5, Y):
    return tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z5, labels=Y))

这篇关于AttributeError:“ NoneType”对象没有属性“ dtype”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆