ValueError:无法将NumPy数组转换为张量(不支持的对象类型numpy.ndarray).试图预测特斯拉股票 [英] ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). in trying to predict tesla stock

查看:184
本文介绍了ValueError:无法将NumPy数组转换为张量(不支持的对象类型numpy.ndarray).试图预测特斯拉股票的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最后,您可以看到我已经尝试将其转换为numpy数组,但我不明白为什么tensorflow不支持它?我查看了其他相关页面,但似乎无济于事.为了使模型正确地适合模型,我还需要对数据进行其他格式化吗?

In the end you can see that i have tried converting this into a numpy array but I don't understand why tensorflow dosen't support it? I have looked at the other related pages but none seemed to help. Is there some other format i have to do to the data in order to properly fit in model?

这是keras说的: x
训练数据的向量,矩阵或数组(如果模型具有多个输入,则列出该数据).如果模型中的所有输入均已命名,则还可以传递将输入名称映射到数据的列表.如果从框架本机张量(例如TensorFlow数据张量)馈送,则x可以为NULL(默认值).

this is what keras says: x
Vector, matrix, or array of training data (or list if the model has multiple inputs). If all inputs in the model are named, you can also pass a list mapping input names to data. x can be NULL (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).

y
目标(标签)数据的向量,矩阵或数组(如果模型具有多个输出,则列出该向量).如果模型中的所有输出均已命名,则还可以传递将输出名称映射到数据的列表.如果从框架本机张量(例如TensorFlow数据张量)馈送,则y可以为NULL(默认值).

y
Vector, matrix, or array of target (label) data (or list if the model has multiple outputs). If all outputs in the model are named, you can also pass a list mapping output names to data. y can be NULL (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).

import pandas as pd
from sklearn import preprocessing
from collections import deque
import numpy as np
import random as rd
import time
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM, BatchNormalization



data = pd.read_csv("TSLA.csv")

data.set_index("Date", inplace=True)
data = data[["Close", "Volume"]]

Back_period_history = 100
Future_predict = 10


def classify(current, future):
    if float(future) > float(current):
        return 1
    else:
        return 0


data["future"] = data["Close"].shift(-Future_predict)
data["target"] = list(map(classify, data["Close"], data["future"]))


#print(data.head(20))

times = sorted(data.index.values)
last_10pct = times[-int(0.1*len(times))]

validation_data = data[(data.index >= last_10pct)]
data = data[(data.index < last_10pct)]

def preproccesing(data):
    data = data.drop("future", 1)

    for col in data.columns:
        if col != "target":
            data[col] = data[col].pct_change()
            data.dropna(inplace=True)
            data[col] = preprocessing.scale(data[col].values)
        data.dropna(inplace = True)

        sequential_data = []
        prev_days = deque(maxlen=Back_period_history)
        for i in data.values:
            prev_days.append([n for n in i[:-1]])
            if len(prev_days) == Back_period_history:
                sequential_data.append([np.array(prev_days), i[-1]])

        rd.shuffle(sequential_data)

        buys = []
        sells = []

        for seq, target in sequential_data:
            if target == 0:
                sells.append([seq, target])
            elif target == 1:
                buys.append([seq,target])

        rd.shuffle(buys)
        rd.shuffle(sells)

        lower = min(len(buys), len(sells))

        buys = buys[:lower]
        sells = sells[:lower]

        sequential_data = buys+sells

        rd.shuffle(sequential_data)

        X = []
        y = []

        for seq, target in sequential_data:
            X.append(sequential_data)
            y.append(target)

        return np.array(X),y


train_x, train_y = preproccesing(data)
validation_x, validation_y = preproccesing(validation_data)

model = Sequential()

model.add(LSTM(
    128, input_shape = (train_x.shape[1:]), activation = "relu", return_sequences = True
))
model.add(Dropout(0.2))
model.add(BatchNormalization())

model.add(LSTM(
    128, input_shape = (train_x.shape[1:]), activation = "relu", return_sequences = True
))
model.add(Dropout(0.2))
model.add(BatchNormalization())

model.add(LSTM(
    128, input_shape = (train_x.shape[1:]), activation = "relu", return_sequences = True
))
model.add(Dropout(0.2))
model.add(BatchNormalization())

model.add(Dense(32, activation = "relu"))
model.add(Dropout(0.2))

model.add(Dense(2, activation = "softmax"))

opt = tf.keras.optimizers.Adam()

model.compile(loss="mse", optimizer=opt, metrics=["accuracy"])

train_x = np.asarray(train_x)
train_y = np.asarray(train_y)
validation_x = np.asarray(validation_x)
validation_y = np.asarray(validation_y)

history = model.fit(train_x, train_y, batch_size = 64, epochs = 7, validation_data = (validation_x, validation_y))```

 

推荐答案

此方法有效 tf.convert_to_tensor(y)

这篇关于ValueError:无法将NumPy数组转换为张量(不支持的对象类型numpy.ndarray).试图预测特斯拉股票的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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