質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

371閲覧

tensorflow 時系列予測 AttributeError

dusty

総合スコア0

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2023/03/12 11:56

編集2023/03/12 11:58

tensorflowの時系列予測においてのエラーです。
URL:https://www.tensorflow.org/tutorials/structured_data/time_series?hl=ja

File "c:\users\user\desktop\タイトル無し2.py", line 222, in make_dataset
ds = tf.keras.utils.timeseries_dataset_from_array(

AttributeError: module 'tensorflow.keras.utils' has no attribute 'timeseries_dataset_from_array'

以下のプログラムを実行するとこのエラーが発生します。ご教授くだい。
Pythonの初学者です。

Python

1import os 2import datetime 3 4import IPython 5import IPython.display 6import matplotlib as mpl 7import matplotlib.pyplot as plt 8import numpy as np 9import pandas as pd 10import seaborn as sns 11import tensorflow as tf 12 13mpl.rcParams['figure.figsize'] = (8, 6) 14mpl.rcParams['axes.grid'] = False 15zip_path = tf.keras.utils.get_file( 16 origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip', 17 fname='jena_climate_2009_2016.csv.zip', 18 extract=True) 19csv_path, _ = os.path.splitext(zip_path) 20df = pd.read_csv(csv_path) 21# Slice [start:stop:step], starting from index 5 take every 6th record. 22df = df[5::6] 23 24date_time = pd.to_datetime(df.pop('Date Time'), format='%d.%m.%Y %H:%M:%S') 25df.head() 26plot_cols = ['T (degC)', 'p (mbar)', 'rho (g/m**3)'] 27plot_features = df[plot_cols] 28plot_features.index = date_time 29_ = plot_features.plot(subplots=True) 30 31plot_features = df[plot_cols][:480] 32plot_features.index = date_time[:480] 33_ = plot_features.plot(subplots=True) 34df.describe().transpose() 35wv = df['wv (m/s)'] 36bad_wv = wv == -9999.0 37wv[bad_wv] = 0.0 38 39max_wv = df['max. wv (m/s)'] 40bad_max_wv = max_wv == -9999.0 41max_wv[bad_max_wv] = 0.0 42 43# The above inplace edits are reflected in the DataFrame. 44df['wv (m/s)'].min() 45plt.hist2d(df['wd (deg)'], df['wv (m/s)'], bins=(50, 50), vmax=400) 46plt.colorbar() 47plt.xlabel('Wind Direction [deg]') 48plt.ylabel('Wind Velocity [m/s]') 49wv = df.pop('wv (m/s)') 50max_wv = df.pop('max. wv (m/s)') 51 52# Convert to radians. 53wd_rad = df.pop('wd (deg)')*np.pi / 180 54 55# Calculate the wind x and y components. 56df['Wx'] = wv*np.cos(wd_rad) 57df['Wy'] = wv*np.sin(wd_rad) 58 59# Calculate the max wind x and y components. 60df['max Wx'] = max_wv*np.cos(wd_rad) 61df['max Wy'] = max_wv*np.sin(wd_rad) 62plt.hist2d(df['Wx'], df['Wy'], bins=(50, 50), vmax=400) 63plt.colorbar() 64plt.xlabel('Wind X [m/s]') 65plt.ylabel('Wind Y [m/s]') 66ax = plt.gca() 67ax.axis('tight') 68timestamp_s = date_time.map(pd.Timestamp.timestamp) 69day = 24*60*60 70year = (365.2425)*day 71 72df['Day sin'] = np.sin(timestamp_s * (2 * np.pi / day)) 73df['Day cos'] = np.cos(timestamp_s * (2 * np.pi / day)) 74df['Year sin'] = np.sin(timestamp_s * (2 * np.pi / year)) 75df['Year cos'] = np.cos(timestamp_s * (2 * np.pi / year)) 76plt.plot(np.array(df['Day sin'])[:25]) 77plt.plot(np.array(df['Day cos'])[:25]) 78plt.xlabel('Time [h]') 79plt.title('Time of day signal') 80fft = tf.signal.rfft(df['T (degC)']) 81f_per_dataset = np.arange(0, len(fft)) 82 83n_samples_h = len(df['T (degC)']) 84hours_per_year = 24*365.2524 85years_per_dataset = n_samples_h/(hours_per_year) 86 87f_per_year = f_per_dataset/years_per_dataset 88plt.step(f_per_year, np.abs(fft)) 89plt.xscale('log') 90plt.ylim(0, 400000) 91plt.xlim([0.1, max(plt.xlim())]) 92plt.xticks([1, 365.2524], labels=['1/Year', '1/day']) 93_ = plt.xlabel('Frequency (log scale)') 94column_indices = {name: i for i, name in enumerate(df.columns)} 95 96n = len(df) 97train_df = df[0:int(n*0.7)] 98val_df = df[int(n*0.7):int(n*0.9)] 99test_df = df[int(n*0.9):] 100 101num_features = df.shape[1] 102train_mean = train_df.mean() 103train_std = train_df.std() 104 105train_df = (train_df - train_mean) / train_std 106val_df = (val_df - train_mean) / train_std 107test_df = (test_df - train_mean) / train_std 108df_std = (df - train_mean) / train_std 109df_std = df_std.melt(var_name='Column', value_name='Normalized') 110plt.figure(figsize=(12, 6)) 111ax = sns.violinplot(x='Column', y='Normalized', data=df_std) 112_ = ax.set_xticklabels(df.keys(), rotation=90) 113class WindowGenerator(): 114 def __init__(self, input_width, label_width, shift, 115 train_df=train_df, val_df=val_df, test_df=test_df, 116 label_columns=None): 117 # Store the raw data. 118 self.train_df = train_df 119 self.val_df = val_df 120 self.test_df = test_df 121 122 # Work out the label column indices. 123 self.label_columns = label_columns 124 if label_columns is not None: 125 self.label_columns_indices = {name: i for i, name in 126 enumerate(label_columns)} 127 self.column_indices = {name: i for i, name in 128 enumerate(train_df.columns)} 129 130 # Work out the window parameters. 131 self.input_width = input_width 132 self.label_width = label_width 133 self.shift = shift 134 135 self.total_window_size = input_width + shift 136 137 self.input_slice = slice(0, input_width) 138 self.input_indices = np.arange(self.total_window_size)[self.input_slice] 139 140 self.label_start = self.total_window_size - self.label_width 141 self.labels_slice = slice(self.label_start, None) 142 self.label_indices = np.arange(self.total_window_size)[self.labels_slice] 143 144 def __repr__(self): 145 return '\n'.join([ 146 f'Total window size: {self.total_window_size}', 147 f'Input indices: {self.input_indices}', 148 f'Label indices: {self.label_indices}', 149 f'Label column name(s): {self.label_columns}']) 150w1 = WindowGenerator(input_width=24, label_width=1, shift=24, 151 label_columns=['T (degC)']) 152w1 153w2 = WindowGenerator(input_width=6, label_width=1, shift=1, 154 label_columns=['T (degC)']) 155w2 156def split_window(self, features): 157 inputs = features[:, self.input_slice, :] 158 labels = features[:, self.labels_slice, :] 159 if self.label_columns is not None: 160 labels = tf.stack( 161 [labels[:, :, self.column_indices[name]] for name in self.label_columns], 162 axis=-1) 163 164 # Slicing doesn't preserve static shape information, so set the shapes 165 # manually. This way the `tf.data.Datasets` are easier to inspect. 166 inputs.set_shape([None, self.input_width, None]) 167 labels.set_shape([None, self.label_width, None]) 168 169 return inputs, labels 170 171WindowGenerator.split_window = split_window 172# Stack three slices, the length of the total window. 173example_window = tf.stack([np.array(train_df[:w2.total_window_size]), 174 np.array(train_df[100:100+w2.total_window_size]), 175 np.array(train_df[200:200+w2.total_window_size])]) 176 177example_inputs, example_labels = w2.split_window(example_window) 178 179print('All shapes are: (batch, time, features)') 180print(f'Window shape: {example_window.shape}') 181print(f'Inputs shape: {example_inputs.shape}') 182print(f'Labels shape: {example_labels.shape}') 183w2.example = example_inputs, example_labels 184def plot(self, model=None, plot_col='T (degC)', max_subplots=3): 185 inputs, labels = self.example 186 plt.figure(figsize=(12, 8)) 187 plot_col_index = self.column_indices[plot_col] 188 max_n = min(max_subplots, len(inputs)) 189 for n in range(max_n): 190 plt.subplot(max_n, 1, n+1) 191 plt.ylabel(f'{plot_col} [normed]') 192 plt.plot(self.input_indices, inputs[n, :, plot_col_index], 193 label='Inputs', marker='.', zorder=-10) 194 195 if self.label_columns: 196 label_col_index = self.label_columns_indices.get(plot_col, None) 197 else: 198 label_col_index = plot_col_index 199 200 if label_col_index is None: 201 continue 202 203 plt.scatter(self.label_indices, labels[n, :, label_col_index], 204 edgecolors='k', label='Labels', c='#2ca02c', s=64) 205 if model is not None: 206 predictions = model(inputs) 207 plt.scatter(self.label_indices, predictions[n, :, label_col_index], 208 marker='X', edgecolors='k', label='Predictions', 209 c='#ff7f0e', s=64) 210 211 if n == 0: 212 plt.legend() 213 214 plt.xlabel('Time [h]') 215 216WindowGenerator.plot = plot 217w2.plot() 218w2.plot(plot_col='p (mbar)') 219 220def make_dataset(self, data): 221 data = np.array(data, dtype=np.float32) 222 ds = tf.keras.utils.timeseries_dataset_from_array( 223 data=data, 224 targets=None, 225 sequence_length=self.total_window_size, 226 sequence_stride=1, 227 shuffle=True, 228 batch_size=32,) 229 230 231 ds = ds.map(self.split_window) 232 233 return ds 234 235WindowGenerator.make_dataset = make_dataset 236@property 237def train(self): 238 return self.make_dataset(self.train_df) 239 240@property 241def val(self): 242 return self.make_dataset(self.val_df) 243 244@property 245def test(self): 246 return self.make_dataset(self.test_df) 247 248@property 249def example(self): 250 """Get and cache an example batch of `inputs, labels` for plotting.""" 251 result = getattr(self, '_example', None) 252 if result is None: 253 # No example batch was found, so get one from the `.train` dataset 254 result = next(iter(self.train)) 255 # And cache it for next time 256 self._example = result 257 return result 258 259WindowGenerator.train = train 260WindowGenerator.val = val 261WindowGenerator.test = test 262WindowGenerator.example = example 263# Each element is an (inputs, label) pair. 264w2.train.element_spec 265for example_inputs, example_labels in w2.train.take(1): 266 print(f'Inputs shape (batch, time, features): {example_inputs.shape}') 267 print(f'Labels shape (batch, time, features): {example_labels.shape}') 268

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2023/03/12 12:01

tensorflowのバージョンは何でしょうか?
dusty

2023/03/12 12:05

2.3です
meg_

2023/03/12 12:54

@dustyさん 質問に追記ください。 @melianさん 回答欄に回答してください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問