• bitcoinBitcoin(BTC)$75,920.00-5.83%
  • ethereumEthereum(ETH)$2,232.71-8.09%
  • tetherTether(USDT)$1.00-0.03%
  • binancecoinBNB(BNB)$692.83-3.27%
  • rippleXRP(XRP)$1.21-7.66%
  • usd-coinUSDC(USDC)$1.00-0.02%
  • solanaSolana(SOL)$90.01-6.82%
  • tronTRON(TRX)$0.318090-0.34%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.04-1.02%
  • zcashZcash(ZEC)$1,309.02-0.80%
  • HyperliquidHyperliquid(HYPE)$77.57-7.81%
  • moneroMonero(XMR)$619.92-2.64%
  • dogecoinDogecoin(DOGE)$0.072078-6.64%
  • USDSUSDS(USDS)$1.000.01%
  • whitebitWhiteBIT Coin(WBT)$72.97-6.48%
  • leo-tokenLEO Token(LEO)$9.35-0.03%
  • chainlinkChainlink(LINK)$10.88-5.93%
  • cardanoCardano(ADA)$0.184589-7.02%
  • bitcoin-cashBitcoin Cash(BCH)$276.20-2.02%
  • stellarStellar(XLM)$0.155627-7.58%
  • nearNEAR Protocol(NEAR)$3.70-8.67%
  • Ethena USDeEthena USDe(USDE)$1.00-0.06%
  • daiDai(DAI)$1.000.01%
  • RainRain(RAIN)$0.0061102.18%
  • uniswapUniswap(UNI)$6.97-9.93%
  • litecoinLitecoin(LTC)$52.42-6.96%
  • CantonCanton(CC)$0.097212-4.38%
  • avalanche-2Avalanche(AVAX)$8.31-5.86%
  • USD1USD1(USD1)$1.00-0.07%
  • suiSui(SUI)$0.86-8.03%
  • tether-goldTether Gold(XAUT)$4,032.39-1.89%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.11-5.97%
  • hedera-hashgraphHedera(HBAR)$0.068549-6.48%
  • Global DollarGlobal Dollar(USDG)$1.000.00%
  • quant-networkQuant(QNT)$190.10-7.20%
  • shiba-inuShiba Inu(SHIB)$0.000005-3.36%
  • paypal-usdPayPal USD(PYUSD)$1.000.01%
  • Ripple USDRipple USD(RLUSD)$1.000.03%
  • BittensorBittensor(TAO)$219.80-7.37%
  • crypto-com-chainCronos(CRO)$0.049200-6.05%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.15%
  • okbOKB(OKB)$105.62-5.89%
  • EthenaEthena(ENA)$0.163313-11.06%
  • Circle USYCCircle USYC(USYC)$1.140.01%
  • pepePepe(PEPE)$0.000005-4.00%
  • aaveAave(AAVE)$130.31-1.82%
  • MemeCoreMemeCore(M)$0.84-0.56%
  • Spiko Amundi Overnight Swap Fund (EUR)Spiko Amundi Overnight Swap Fund (EUR)(EURSAFO)$1.14-0.47%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • OndoOndo(ONDO)$0.374226-9.76%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

Building an Advanced Convolutional Neural Network with Attention for DNA Sequence Classification and Interpretability

September 16, 2025
in AI & Technology
Reading Time: 3 mins read
A A
Building an Advanced Convolutional Neural Network with Attention for DNA Sequence Classification and Interpretability
ShareShareShareShareShare
class DNASequenceClassifier:
   def __init__(self, sequence_length=200, num_classes=2):
       self.sequence_length = sequence_length
       self.num_classes = num_classes
       self.model = None
       self.history = None
      
   def one_hot_encode(self, sequences):
       mapping = {'A': 0, 'T': 1, 'G': 2, 'C': 3}
       encoded = np.zeros((len(sequences), self.sequence_length, 4))
      
       for i, seq in enumerate(sequences):
           for j, nucleotide in enumerate(seq[:self.sequence_length]):
               if nucleotide in mapping:
                   encoded[i, j, mapping[nucleotide]] = 1
       return encoded
  
   def attention_layer(self, inputs, name="attention"):
       attention_weights = layers.Dense(1, activation='tanh', name=f"{name}_weights")(inputs)
       attention_weights = layers.Flatten()(attention_weights)
       attention_weights = layers.Activation('softmax', name=f"{name}_softmax")(attention_weights)
       attention_weights = layers.RepeatVector(inputs.shape[-1])(attention_weights)
       attention_weights = layers.Permute([2, 1])(attention_weights)
      
       attended = layers.Multiply(name=f"{name}_multiply")([inputs, attention_weights])
       return layers.GlobalMaxPooling1D()(attended)
  
   def build_model(self):
       inputs = layers.Input(shape=(self.sequence_length, 4), name="dna_input")
      
       conv_layers = []
       filter_sizes = [3, 7, 15, 25]
      
       for i, filter_size in enumerate(filter_sizes):
           conv = layers.Conv1D(
               filters=64,
               kernel_size=filter_size,
               activation='relu',
               padding='same',
               name=f"conv_{filter_size}"
           )(inputs)
           conv = layers.BatchNormalization(name=f"bn_conv_{filter_size}")(conv)
           conv = layers.Dropout(0.2, name=f"dropout_conv_{filter_size}")(conv)
          
           attended = self.attention_layer(conv, name=f"attention_{filter_size}")
           conv_layers.append(attended)
      
       if len(conv_layers) > 1:
           merged = layers.Concatenate(name="concat_multiscale")(conv_layers)
       else:
           merged = conv_layers[0]
      
       dense = layers.Dense(256, activation='relu', name="dense_1")(merged)
       dense = layers.BatchNormalization(name="bn_dense_1")(dense)
       dense = layers.Dropout(0.5, name="dropout_dense_1")(dense)
      
       dense = layers.Dense(128, activation='relu', name="dense_2")(dense)
       dense = layers.BatchNormalization(name="bn_dense_2")(dense)
       dense = layers.Dropout(0.3, name="dropout_dense_2")(dense)
      
       if self.num_classes == 2:
           outputs = layers.Dense(1, activation='sigmoid', name="output")(dense)
           loss="binary_crossentropy"
           metrics = ['accuracy', 'precision', 'recall']
       else:
           outputs = layers.Dense(self.num_classes, activation='softmax', name="output")(dense)
           loss="categorical_crossentropy"
           metrics = ['accuracy']
      
       self.model = keras.Model(inputs=inputs, outputs=outputs, name="DNA_CNN_Classifier")
      
       optimizer = keras.optimizers.Adam(
           learning_rate=0.001,
           beta_1=0.9,
           beta_2=0.999,
           epsilon=1e-7
       )
      
       self.model.compile(
           optimizer=optimizer,
           loss=loss,
           metrics=metrics
       )
      
       return self.model
  
   def generate_synthetic_data(self, n_samples=10000):
       sequences = []
       labels = []
      
       positive_motifs = ['TATAAA', 'CAAT', 'GGGCGG', 'TTGACA']
       negative_motifs = ['AAAAAAA', 'TTTTTTT', 'CCCCCCC', 'GGGGGGG']
      
       nucleotides = ['A', 'T', 'G', 'C']
      
       for i in range(n_samples):
           sequence="".join(random.choices(nucleotides, k=self.sequence_length))
          
           if i < n_samples // 2:
               motif = random.choice(positive_motifs)
               pos = random.randint(0, self.sequence_length - len(motif))
               sequence = sequence[:pos] + motif + sequence[pos + len(motif):]
               label = 1
           else:
               if random.random() < 0.3:
                   motif = random.choice(negative_motifs)
                   pos = random.randint(0, self.sequence_length - len(motif))
                   sequence = sequence[:pos] + motif + sequence[pos + len(motif):]
               label = 0
          
           sequences.append(sequence)
           labels.append(label)
      
       return sequences, np.array(labels)
  
   def train(self, X_train, y_train, X_val, y_val, epochs=50, batch_size=32):
       callbacks = [
           keras.callbacks.EarlyStopping(
               monitor="val_loss",
               patience=10,
               restore_best_weights=True
           ),
           keras.callbacks.ReduceLROnPlateau(
               monitor="val_loss",
               factor=0.5,
               patience=5,
               min_lr=1e-6
           )
       ]
      
       self.history = self.model.fit(
           X_train, y_train,
           validation_data=(X_val, y_val),
           epochs=epochs,
           batch_size=batch_size,
           callbacks=callbacks,
           verbose=1
       )
      
       return self.history
  
   def evaluate_and_visualize(self, X_test, y_test):
       y_pred_proba = self.model.predict(X_test)
       y_pred = (y_pred_proba > 0.5).astype(int).flatten()
      
       print("Classification Report:")
       print(classification_report(y_test, y_pred))
      
       fig, axes = plt.subplots(2, 2, figsize=(15, 10))
      
       axes[0,0].plot(self.history.history['loss'], label="Training Loss")
       axes[0,0].plot(self.history.history['val_loss'], label="Validation Loss")
       axes[0,0].set_title('Training History - Loss')
       axes[0,0].set_xlabel('Epoch')
       axes[0,0].set_ylabel('Loss')
       axes[0,0].legend()
      
       axes[0,1].plot(self.history.history['accuracy'], label="Training Accuracy")
       axes[0,1].plot(self.history.history['val_accuracy'], label="Validation Accuracy")
       axes[0,1].set_title('Training History - Accuracy')
       axes[0,1].set_xlabel('Epoch')
       axes[0,1].set_ylabel('Accuracy')
       axes[0,1].legend()
      
       cm = confusion_matrix(y_test, y_pred)
       sns.heatmap(cm, annot=True, fmt="d", ax=axes[1,0], cmap='Blues')
       axes[1,0].set_title('Confusion Matrix')
       axes[1,0].set_ylabel('Actual')
       axes[1,0].set_xlabel('Predicted')
      
       axes[1,1].hist(y_pred_proba[y_test==0], bins=50, alpha=0.7, label="Negative", density=True)
       axes[1,1].hist(y_pred_proba[y_test==1], bins=50, alpha=0.7, label="Positive", density=True)
       axes[1,1].set_title('Prediction Score Distribution')
       axes[1,1].set_xlabel('Prediction Score')
       axes[1,1].set_ylabel('Density')
       axes[1,1].legend()
      
       plt.tight_layout()
       plt.show()
      
       return y_pred, y_pred_proba

Credit: Source link

YOU MAY ALSO LIKE

Airbnb Discloses AI Lab Deal With Investment and Licensing Rights – Unite.AI

Perplexity Cuts Agent API Research Costs and Adds Ultra Effort – Unite.AI

ShareTweetSendSharePin

Related Posts

Airbnb Discloses AI Lab Deal With Investment and Licensing Rights – Unite.AI
AI & Technology

Airbnb Discloses AI Lab Deal With Investment and Licensing Rights – Unite.AI

November 6, 2026
Perplexity Cuts Agent API Research Costs and Adds Ultra Effort – Unite.AI
AI & Technology

Perplexity Cuts Agent API Research Costs and Adds Ultra Effort – Unite.AI

November 5, 2026
Blue Origin’s New Glenn Launch Delay Will Continue Into 2027
AI & Technology

Blue Origin’s New Glenn Launch Delay Will Continue Into 2027

November 5, 2026
Five9 Agrees to Buy Level AI and Broaden CX AI Distribution – Unite.AI
AI & Technology

Five9 Agrees to Buy Level AI and Broaden CX AI Distribution – Unite.AI

November 5, 2026
Next Post
Amazon, Google Probed by FTC Over Search Ad Practices

Amazon, Google Probed by FTC Over Search Ad Practices

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Coinbase Global, Inc. 2026 Q3 – Results – Earnings Call Presentation (NASDAQ:COIN) 2026-11-02

Coinbase Global, Inc. 2026 Q3 – Results – Earnings Call Presentation (NASDAQ:COIN) 2026-11-02

November 2, 2026
What Is Earnings Season and What Does It Mean For You?

What Is Earnings Season and What Does It Mean For You?

November 6, 2026
‘Seismic shift’: World reacts to US midterm election results – Al Jazeera

‘Seismic shift’: World reacts to US midterm election results – Al Jazeera

November 4, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!