FrontPage
B3 前期授業スケジュール
月曜日 火曜日 水曜日 木曜日 金曜日
1-2 研究会
3-4 卒論1 研究会
5-6 卒論1 ディジタル信号処理 卒論1 卒論1
7-8 技術者倫理
9-10 研究会 &size(px){Text you want to change};
11-12
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "ダッシュストーム.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
&ref(): File not found: "栗松.jpg" at page "中島";
メモ
n problem.solve(solver="OSQP", max_iter=self.max_iter)\n\n if problem.status != "optimal":\n raise ConvergenceWarning(\n f"Solver did not reach optimum (Status: {problem.status})"\n )\n\n beta_sol = np.concatenate([b.value for b in beta_variables], axis=0)\n beta_sol[np.abs(beta_sol) < self.tol] = 0\n\n intercept, coef = beta_sol[0], beta_sol[1:]\n coef = np.maximum(coef, 0) if self.positive else coef\n\n return coef, intercept\n\n\nfrom sklearn.linear_model import ElasticNetCV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.datasets import make_regression\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\n\n# CSVファイルのパスを指定してください\nfile_path = "C:/Users/nt011/Desktop/研究/富山取引のほう富山市のみ/変数選択/変数作成後新新.csv"\n\n# CSVファイルの読み込み\ndf = pd.read_csv(file_path, encoding='cp932') # 文字コードが異なる場合は、'utf-8' を他のエンコーディングに変更してください\n\n# 特徴量とターゲットの分割\nX = df.drop(columns=['取引価格(㎡単価)']) # 取引価格(㎡単価)をyとして分離\ny = df['取引価格(㎡単価)'] # ターゲット変数\n\n# 🔥 標準化の実施\nscaler_X = StandardScaler()\nscaler_y = StandardScaler()\n\nX_scaled = scaler_X.fit_transform(X) # Xの標準化\ny_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel() # yの標準化\n\n\n# データ分割\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.35, random_state=42)\n\n# 訓練データの一部を使用\nX_sample, _, y_sample, _ = train_test_split(X_train, y_train, test_size=0.8, random_state=42)\n\n# 第一段階: ElasticNetCVを使用した最適パラメータの導出\nenet_cv = ElasticNetCV(\n l1_ratio=np.linspace(0.0001, 1, 25), # l1_ratioの候補\n alphas=np.logspace(-5, 0, 25), # alphaの候補\n cv=5, # 交差検証の分割数\n random_state=42,\n n_jobs=-1\n)\nenet_cv.fit(X_train, y_train)\n\n# 第一段階の最適パラメータと係数を取得\nalpha1_opt = enet_cv.alpha_\nl1_ratio1_opt = enet_cv.l1_ratio_\nenet_coef = enet_cv.coef_\n\nprint(f"第一段階の最適パラメータ: alpha1={alpha1_opt}, l1_ratio1={l1_ratio1_opt}"))
やること
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_regression
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# CSVファイルのパスを指定してください
file_path = "C:/Users/nt011/Desktop/研究/富山取引のほう富山市のみ/変数選択/変数作成後新.csv"
# CSVファイルの読み込み
df = pd.read_csv(file_path, encoding='cp932') # 文字コードが異なる場合は、'utf-8' を他のエンコーディングに変更してください
# 特徴量とターゲットの分割
X = df.drop(columns=['取引価格(㎡単価)']) # 取引価格(㎡単価)をyとして分離
y = df['取引価格(㎡単価)'] # ターゲット変数
# 🔥 標準化の実施
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_scaled = scaler_X.fit_transform(X) # Xの標準化
y_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel() # yの標準化
# データ分割
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.2, random_state=42)
# 訓練データの一部を使用
X_sample, _, y_sample, _ = train_test_split(X_train, y_train, test_size=0.8, random_state=42)
# 2. パラメータグリッドの設定
param_grid = {
'alpha': np.logspace(-5, 0, 10), # alpha1の探索範囲 (正則化パラメータ)
'l1_ratio': np.linspace(0.0001, 1.0, 10) # l1_ratio1の探索範囲 (L1とL2の比率)
}
# パラメータ名を変更(alpha -> alpha1, l1_ratio -> l1_ratio1)
param_grid = {'alpha1': param_grid['alpha'], 'l1_ratio1': param_grid['l1_ratio']}
# 3. ElasticNetモデルの初期化
elastic_net = ElasticNet(max_iter=10000, random_state=42)
# 4. グリッドサーチCVの設定
grid_search = GridSearchCV(
estimator=elastic_net,
param_grid={'alpha': param_grid['alpha1'], 'l1_ratio': param_grid['l1_ratio1']}, # 変更した名前に対応
cv=5, # 5分割交差検証
scoring='neg_mean_squared_error', # 評価指標: 平均二乗誤差の負値
verbose=1,
n_jobs=-1 # 並列実行
)
# 5. グリッドサーチの実行
grid_search.fit(X_sample, y_sample)
# 6. 最適なパラメータとスコアの取得
best_params = grid_search.best_params_
best_params_renamed = {'alpha1': best_params['alpha'], 'l1_ratio1': best_params['l1_ratio']}
best_score = grid_search.best_score_
print("最適なパラメータ:")
print(best_params_renamed)
print("最良のスコア (平均二乗誤差の負値):")
print(best_score)
class TQDMGridSearchCV(GridSearchCV):
def __init__(self, estimator, param_grid, cv=5, scoring=None, n_jobs=None, verbose=0,
refit=True, return_train_score=True, pre_dispatch='2*n_jobs', error_score='raise', **kwargs):
# iid引数を削除して、super()に渡さない
super().__init__(estimator=estimator, param_grid=param_grid, cv=cv, scoring=scoring,
n_jobs=n_jobs, verbose=verbose, refit=refit, return_train_score=return_train_score,
pre_dispatch=pre_dispatch, error_score=error_score, **kwargs)
# tqdmを使って進捗表示
self.tqdm = tqdm(total=1, position=0, leave=True)
def fit(self, X, y=None, **fit_params):
# 進捗バーを更新
self.tqdm.set_description("Fitting model")
result = super().fit(X, y, **fit_params)
self.tqdm.close() # 進捗バーを閉じる
return result
# 第二段階のGridSearchCVで交差検証(進捗表示を追加)
grid_search = TQDMGridSearchCV(
estimator=model,
param_grid=param_grid,
cv=5, # 交差検証の分割数
scoring='neg_mean_squared_error', # 評価指標(MSEの負の値を使用)
#n_jobs=-1, # 並列実行
verbose=1 # 実行状況を表示しない
)
import numba
from numba import jit
import numpy as np
import pandas as pd
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
# Numbaを使った交差検証の高速化
@jit(nopython=True)
def cross_val_score_numba(X, y, model, cv=5):
"""
Numbaを使用した交差検証の実装
"""
n_samples = X.shape[0]
fold_size = n_samples // cv
scores = np.zeros(cv)
for i in range(cv):
# フォールドの分割
val_idx = list(range(i * fold_size, (i + 1) * fold_size))
train_idx = list(set(range(n_samples)) - set(val_idx))
X_train, X_val = X[train_idx], X[val_idx]
y_train, y_val = y[train_idx], y[val_idx]
model.fit(X_train, y_train)
y_pred = model.predict(X_val)
# MSEスコアの計算
scores[i] = mean_squared_error(y_val, y_pred)
return scores
# CSVファイルのパスを指定してください
file_path = "C:/Users/tn011/Desktop/変数作成後新新.csv"
# CSVファイルの読み込み
df = pd.read_csv(file_path, encoding='cp932')
# 特徴量とターゲットの分割
X = df.drop(columns=['取引価格(㎡単価)'])
y = df['取引価格(㎡単価)']
# 標準化の実施
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_scaled = scaler_X.fit_transform(X)
y_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1)).ravel()
# 訓練データとテストデータに分割
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.35, random_state=42)
# 第一段階のElasticNetのハイパーパラメータチューニング
alpha_values = np.logspace(-5, 0, 25)
l1_ratio_values = np.linspace(0.0001, 1, 25)
best_score = float('inf')
best_alpha = None
best_l1_ratio = None
best_model = None
# numbaを使用した交差検証を実行
for alpha in alpha_values:
for l1_ratio in l1_ratio_values:
model = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=10000)
scores = cross_val_score(model, X_train, y_train, cv=5, scoring='neg_mean_squared_error')
mean_score = np.mean(scores)
if mean_score < best_score:
best_score = mean_score
best_alpha1 = alpha
best_l1_ratio1 = l1_ratio
best_model = model
print(f"最適なalpha: {best_alpha1}, 最適なl1_ratio: {best_l1_ratio1}")
# 最適なモデルのトレーニング
best_model.fit(X_train, y_train)
y_pred = best_model.predict(X_test)
# テストデータでの性能を評価
test_score = mean_squared_error(y_test, y_pred)
print(f"テストデータのMSE: {test_score}")