TypeError:将形状转换为TensorShape时出错:int()参数必须是字符串,类似字节的对象或数字,而不是'tuple'。在python中

时间:2019-01-29 05:16:48

标签: python machine-learning keras

运行下面在网上找到的有关定义机器学习模型的代码时,出现此错误:

raise TypeError("Error converting %s to a TensorShape: %s." % (arg_name, e))
TypeError: Error converting shape to a TensorShape: int() argument must be a string, a
bytes-like object or a number, not 'tuple'.

import pandas as pd
import numpy  as np

customers = pd.read_csv('EcommerceCustomers.csv')

X = customers[['Avg. Session Length', 'Time on App', 'Time on Website','Length of Membership']].values
y = customers['Yearly Amount Spent'].values

from sklearn.model_selection import train_test_split

X_training, X_testing, Y_training, Y_testing = train_test_split(X, y, test_size=0.30, random_state=101)

Y_training= np.reshape(Y_training, (-1, 1))
Y_testing= np.reshape(Y_testing, (-1, 1))

from sklearn.preprocessing import MinMaxScaler

X_scaler = MinMaxScaler(feature_range=(0, 1))
Y_scaler = MinMaxScaler(feature_range=(0, 1))

X_scaled_training = X_scaler.fit_transform(X_training)
Y_scaled_training = Y_scaler.fit_transform(Y_training)

X_scaled_testing = X_scaler.fit_transform(X_testing)
Y_scaled_testing = Y_scaler.fit_transform(Y_testing)

print(X_scaled_testing.shape)
print(Y_scaled_testing.shape)

print("Note: Y values were scaled by multiplying by {:.10f} and adding {:.4f}".format(Y_scaler.scale_[0], Y_scaler.min_[0]))

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(50, input_dim=, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss="mean_squared_error", optimizer="adam")

此行出现错误:

model.add(Dense(50, input_dim=, activation='relu'))`

发生此类问题的原因是什么?我尝试了许多示例,但找不到解决方案。

3 个答案:

答案 0 :(得分:0)

在您的代码中,此行有一个错字:

model.add(Dense(50, input_dim=, activation='relu'))

参数input_dim应该是您计划馈送到该层的数组的形状(展平)。我实际上建议改用input_shape

尝试一下:

model.add(Dense(50, input_shape=X[0].shape, activation='relu'))

看看keras reference docs

答案 1 :(得分:0)

此行将导致语法错误。 Dense(50, input_dim=, activation='relu')

In [1]: Dense(50, input_dim=, activation='relu')
  File "<ipython-input-2-ed8b4d6f4769>", line 1
    Dense(50, input_dim=, activation='relu')
                        ^
SyntaxError: invalid syntax

致电input_dim时不能将keras.layers.Dense留空,您必须通过input_diminput_shape

model.add(Dense(50, input_dim=(16, ), activation='relu'))

答案 2 :(得分:0)

我在tensorflow 2.0和新的keras上遇到了相同的问题,我使用了input_dim参数,但我应该这样做input_shape

model_1.add(Dense(10, activation='relu', input_shape=(50,50,3)))