1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【python初学者】csv 書き出しができないケース(tensor→numpy変換、次元数調整)

Posted at

###上手くいかなかった事例

予測
score = net(x_test)

score.dtype
→torch.float32

csv 書き出し
pd.Series(score, name='score').to_csv('submission.csv', index=None, line_terminator='\n')


RuntimeError Traceback (most recent call last)
in ()
1 # csv 書き出し
----> 2 pd.Series(score, name='score').to_csv('submission.csv', index=None, line_terminator='\n')

5 frames
/usr/local/lib/python3.7/dist-packages/torch/_tensor.py in array(self, dtype)
641 return handle_torch_function(Tensor.array, (self,), self, dtype=dtype)
642 if dtype is None:
--> 643 return self.numpy()
644 else:
645 return self.numpy().astype(dtype, copy=False)

RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.

###上手くいった事例

エラー文のUse tensor.detach().numpy() instead.を参考に
以下のようにしてみました。

score = score.detach().numpy()

これでnumpy形式になったので行ける!
と思いきや、

csv 書き出し
pd.Series(score, name='score').to_csv('submission.csv', index=None, line_terminator='\n')

Exception Traceback (most recent call last)
in ()
1 # csv 書き出し
----> 2 pd.Series(score, name='score').to_csv('submission.csv', index=None, line_terminator='\n')

1 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/construction.py in sanitize_array(data, index, dtype, copy, raise_cast_failure)
494 elif subarr.ndim > 1:
495 if isinstance(data, np.ndarray):
--> 496 raise Exception("Data must be 1-dimensional")
497 else:
498 subarr = com.asarray_tuplesafe(data, dtype=dtype)

Exception: Data must be 1-dimensional

今度は、「Data must be 1-dimensional」と言われたので

再度、次元数を確かめたところ
score.ndim
→2

と返されたので
score = np.squeeze(score)
を適用し
score.ndim
→1
次元数を1に変換。

csv 書き出し
pd.Series(score, name='score').to_csv('submission.csv', index=None, line_terminator='\n')

→書き出し成功!!

ポイントは、tensor→numpy形式への変換と、次元数でした。

参考
https://note.nkmk.me/python-numpy-squeeze/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?