【问题标题】:ValueError: x and y must have same first dimension, but have shapes (4200,) and (16800, 1)ValueError: x 和 y 必须具有相同的第一维,但具有形状 (4200,) 和 (16800, 1)
【发布时间】:2018-12-04 20:54:27
【问题描述】:

我使用 SCIKIT-LEARN 创建了一个 SVR 模型,我正在尝试绘制我的数据,但由于某种原因我收到了错误:

ValueError: x 和 y 必须具有相同的第一维,但具有形状 (4200,) 和 (16800, 1)

我已将我的数据拆分为训练和测试数据,训练模型并进行预测。我的代码是:

X_feature = wind_speed

X_feature = X_feature.reshape(-1, 1)## Reshaping array to be 1D from 2D

y_label = Power
y_label = y_label.reshape(-1,1)

    timeseries_split = TimeSeriesSplit(n_splits=3) ## Splitting training testing data into 3 splits
    for train_index, test_index in timeseries_split.split(X_feature):## for loop to obtain print the training and splitting of the data 
    print("Training data:",train_index, "Testing data test:", test_index)#
    X_train, X_test = X_feature[train_index], X_feature[test_index]
    y_train, y_test = y_label[train_index], y_label [test_index]



    timeseries_split = TimeSeriesSplit(n_splits=3) ## Splitting training testing data into 3 splits






    scaler =pre.MinMaxScaler(feature_range=(0,1)).fit(X_train)## Data is being preprocessed then standard deviation 


    scaled_wind_speed_train = scaler.transform(X_train)## Wind speed training data is being scaled and then transformed 

    scaled_wind_speed_test = scaler.transform(X_test)## Wind speed test data is being scaled and then transformed

    SVR_model = svm.SVR(kernel='rbf',C=100,gamma=.001).fit(scaled_wind_speed_train,y_train)



    y_prediction = SVR_model.predict(scaled_wind_speed_test)

    SVR_model.score(scaled_wind_speed_test,y_test)


    rmse=numpy.sqrt(mean_squared_error(y_label,y_prediction))
    print("RMSE:",rmse)


    fig, bx = plt.subplots(figsize=(19,8))
    bx.plot(y_prediction, X_feature,'bs')
    fig.suptitle('Wind Power Prediction v Wind Speed', fontsize=20)
    plt.xlabel('Wind Power Data')
    plt.ylabel('Predicted Power')
    plt.xticks(rotation=30)
    plt.show() 


     fig, bx = plt.subplots(figsize=(19,8))
     bx.plot( y_prediction, y_label)
     fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20)
     plt.xlabel('Wind Power Data')
     plt.ylabel('Predicted Power')


     fig, bx = plt.subplots(figsize=(19,8))
     bx.plot(y_prediction)
     fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20)
     plt.xlabel('Wind Power Data')
     plt.ylabel('Predicted Power')

我相信当我尝试获取该行中的 rmse 时正在生成此代码:

rmse=numpy.sqrt(mean_squared_error(y_label,y_prediction))

当我将此行注释掉并尝试绘制我的数据时也会发生此错误..

我的回溯错误信息是:


ValueError                                Traceback (most recent call last)
<ipython-input-57-ed11a9ca7fd8> in <module>()
     79 
     80     fig, bx = plt.subplots(figsize=(19,8))
---> 81     bx.plot( y_prediction, y_label)
     82     fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20)
     83     plt.xlabel('Wind Power Data')

~/anaconda3_501/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1715                     warnings.warn(msg % (label_namer, func.__name__),
   1716                                   RuntimeWarning, stacklevel=2)
-> 1717             return func(ax, *args, **kwargs)
   1718         pre_doc = inner.__doc__
   1719         if pre_doc is None:

~/anaconda3_501/lib/python3.6/site-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
   1370         kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
   1371 
-> 1372         for line in self._get_lines(*args, **kwargs):
   1373             self.add_line(line)
   1374             lines.append(line)

~/anaconda3_501/lib/python3.6/site-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs)
    402                 this += args[0],
    403                 args = args[1:]
--> 404             for seg in self._plot_args(this, kwargs):
    405                 yield seg
    406 

~/anaconda3_501/lib/python3.6/site-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
    382             x, y = index_of(tup[-1])
    383 
--> 384         x, y = self._xy_from_xy(x, y)
    385 
    386         if self.command == 'plot':

~/anaconda3_501/lib/python3.6/site-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
    241         if x.shape[0] != y.shape[0]:
    242             raise ValueError("x and y must have same first dimension, but "
--> 243                              "have shapes {} and {}".format(x.shape, y.shape))
    244         if x.ndim > 2 or y.ndim > 2:
    245             raise ValueError("x and y can be no greater than 2-D, but have "

ValueError: x and y must have same first dimension, but have shapes (4200,) and (16800, 1)

【问题讨论】:

    标签: python scikit-learn svm


    【解决方案1】:

    我认为你对mean_squared_error 的争论混合了,应该是

    rmse=numpy.sqrt(mean_squared_error(y_test,y_prediction))
    

    更新:根据最新的错误,试试这个

    fig, bx = plt.subplots(figsize=(19,8))
    bx.plot(y_prediction, scaled_wind_speed_test,'bs')
    fig.suptitle('Wind Power Prediction v Wind Speed', fontsize=20)
    plt.xlabel('Wind Power Data')
    plt.ylabel('Predicted Power')
    plt.xticks(rotation=30)
    plt.show() 
    

    更新 2 如果你在另一个情节上遇到错误,试试这个

    fig, bx = plt.subplots(figsize=(19,8))
    bx.plot( y_prediction, y_test)
    fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20)
    plt.xlabel('Wind Power Data')
    plt.ylabel('Predicted Power')
    

    【讨论】:

    • 嗨,我没有意识到这个错误,谢谢。但是我收到一个新错误“ValueError:x 和 y 必须具有相同的第一维,但具有形状 (4200,) 和 (16800, 1)”以及空白图。我已经通过问题更新了 rew 回溯错误。
    • 原理相同。您需要使用 x_test 生成 y_prediction,然后您应该具有相同的大小。此外,您可能需要执行 mean_squared_error(y_test, y_prediction[0]) 才能使其正常工作。
    • 也可以试试mean_squared_error( scaler.transform(y_test), y_prediction[0])
    • 错误跟踪仍然与您的问题之前的相同
    • @levraininjaneer 嗨,当我尝试您建议的那行代码时,我收到错误代码“TypeError:Singleton array 0.1853680535764517 cannot be considered a valid collection。”有什么想法吗?
    【解决方案2】:

    Numpy 的函数mean_squared_error 需要两个大小相同的数组。 您收到的错误意味着这两个的大小不同。

    您可以通过

    检查您的数组大小
    print(array_1.shape)
    print(array_2.shape)
    

    如果你得到的输出是

    output:
    > (4200,)
    > (4200, 1)
    

    你可以通过做来修复

    new_array_2 = array_2.transpose()[0]
    

    然后

    mean_squared_error(array_1, new_array_2)
    

    如果两个输入参数,无论它们是什么,都会为您提供以下形状

    print(array_1.shape)
    print(array_2.shape)
    
    output:
    > (4200,)
    > (16800, 1)
    

    试试

    new_array_1 = scalar.transform(array_1)
    

    new_array_2 = scalar.transform(array_2)
    

    直到您获得具有相同编号的数组,无论是 16800 还是 4200。 一旦你有两个相同尺寸,但其中一个或两个仍然带有额外的尺寸,

    然后再做

    new_new_array_1 = scalar.transform(new_array_1)[0]
    

    并将这些提供给mean_squared_error,例如

    mean_squared_error(new_new_array_1, new_array_2)
    

    【讨论】:

    • 我检查了形状大小,他的形状大小是:shape1: (4200, 1) (4200,)
    • 这是个好消息。然后只需在第一个参数后添加[0],您就应该在做生意,即mean_squared_error(y_test[0], y_prediction)
    • 我认为我们几乎找到了解决方案。我放了一个零,但现在我收到错误消息“ValueError:找到样本数量不一致的输入变量:[1, 4200]”
    • 好的,在这种情况下可以做mean_squared_error(y_test.transpose()[0], y_prediction)
    • 我已经使用“new_array_2 = array_2.transpose()[0]”来改变我的数据的形状,但我仍然得到“shape1: (4200, 1) shape1: (4200,)”。然后我尝试将“new_new_array_1 = scalar.transform(new_array_1)[0]”作为 y_test = scaler.transform(y_test)[0] 但我仍然得到“发现样本数量不一致的输入变量:[1, 4200 ]"
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2021-07-29
    • 2023-03-24
    • 2021-07-31
    相关资源
    最近更新 更多