重新创建代码时遇到问题:Tensorflow NN抛出“ TypeError:无法散列的类型:'sl​​ice''

时间:2019-11-05 17:22:29

标签: python-3.x tensorflow neural-network

我正在尝试通过以下中型文章重新创建代码:https://medium.com/@rajatgupta310198/getting-started-with-neural-network-for-regression-and-tensorflow-58ad3bd75223

我正在努力复制结果,但遇到很多错误。

我对原始文章进行了一些调整:

scaler = MinMaxScaler()#为了规范化数据集,我摆脱了这一点。 删除了非规范化功能。

X_train = scaler.fit_transform(df_train.drop(['Close'],axis = 1).as_matrix()) y_train = scaler.fit_transform(df_train ['Close']。as_matrix())

更改为

X_train = df_train.drop(['Close'],axis = 1) y_train = df_train ['关闭']

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf

df = pd.read_csv('data.csv') # read data set using pandas
print(df.info()) # Overview of dataset
df = df.drop(['Date'],axis=1) # Drop Date feature
df = df.dropna(inplace=False)  # Remove all nan entries.

df = df.drop(['Adj Close','Volume'],axis=1) # Drop Adj close and volume feature
df_train = df[:1059]    # 60% training data and 40% testing data
df_test = df[1059:]

X_train = df_train.drop(['Close'],axis=1)                                                   
y_train = df_train['Close']

X_test = df_test.drop(['Close'],axis=1)
y_test = df_test['Close']

def neural_net_model(X_data,input_dim):
    W_1 = tf.Variable(tf.random_uniform([input_dim,10]))
    b_1 = tf.Variable(tf.zeros([10]))
    layer_1 = tf.add(tf.matmul(X_data,W_1), b_1)
    layer_1 = tf.nn.relu(layer_1)

    # layer 1 multiplying and adding bias then activation function
    W_2 = tf.Variable(tf.random_uniform([10,10]))
    b_2 = tf.Variable(tf.zeros([10]))
    layer_2 = tf.add(tf.matmul(layer_1,W_2), b_2)
    layer_2 = tf.nn.relu(layer_2)
    # layer 2 multiplying and adding bias then activation function
    W_O = tf.Variable(tf.random_uniform([10,1]))
    b_O = tf.Variable(tf.zeros([1]))
    output = tf.add(tf.matmul(layer_2,W_O), b_O)
    # O/p layer multiplying and adding bias then activation function
    # notice output layer has one node only since performing #regression
    return output

xs = tf.placeholder("float")
ys = tf.placeholder("float")
output = neural_net_model(xs,3)
cost = tf.reduce_mean(tf.square(output-ys))
train = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

with tf.Session() as sess:
    # Initiate session and initialize all vaiables
    sess.run(tf.global_variables_initializer())
    saver = tf.train.Saver()
    #saver.restore(sess,'yahoo_dataset.ckpt')
    for i in range(100):
        for j in range(X_train.shape[0]):
            sess.run([cost,train],feed_dict=    {xs:X_train[j,:].reshape(1,3), ys:y_train[j]})
            # Run cost and train with each sample
        c_t.append(sess.run(cost, feed_dict={xs:X_train,ys:y_train}))
        c_test.append(sess.run(cost, feed_dict={xs:X_test,ys:y_test}))
        print('Epoch :',i,'Cost :',c_t[i])
    pred = sess.run(output, feed_dict={xs:X_test})
    # predict output of test data after training
    print('Cost :',sess.run(cost, feed_dict={xs:X_test,ys:y_test}))
    y_test = denormalize(df_test,y_test)
    pred = denormalize(df_test,pred)
    #Denormalize data     
    plt.plot(range(y_test.shape[0]),y_test,label="Original Data")
    plt.plot(range(y_test.shape[0]),pred,label="Predicted Data")
    plt.legend(loc='best')
    plt.ylabel('Stock Value')
    plt.xlabel('Days')
    plt.title('Stock Market Nifty')
    plt.show()
    if input('Save model ? [Y/N]') == 'Y':
        saver.save(sess,'yahoo_dataset.ckpt')
        print('Model Saved')


TypeError跟踪(最近一次通话)  在()中       i在范围(100)中为6:       对于范围(X_train.shape [0])中的j为7: ----> 8 sess.run([cost,train],feed_dict = {xs:X_train [j,:]。reshape(1,3),ys:y_train [j]})       9#运行成本并对每个样本进行培训      10 c_t.append(sess.run(cost,feed_dict = {xs:X_train,ys:y_train}))

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py在 getitem 中(自身,密钥)    2683返回self._getitem_multilevel(键)    2684其他: -> 2685返回self._getitem_column(key)    2686    2687 def _getitem_column(self,key):

_getitem_column中的

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py(self,key)    2690#获取列    第2691章(许我倾城) -> 2692返回self._get_item_cache(key)    2693    2694#重复的列并可能降低维数

_get_item_cache中的

〜\ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ pandas \ core \ generic.py(self,item)    2482“”“返回缓存的项目,该项目表示标签索引器。”“”    2483缓存= self._item_cache -> 2484 res = cache.get(项目)    2485如果res为None:    2486个值= self._data.get(item)

TypeError:不可散列的类型:'sl​​ice'

0 个答案:

没有答案