File size: 2,533 Bytes
303672f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import torch
import torch.nn as nn
import torch.optim as optim
from transformers import AutoModelForCausalLM, AutoTokenizer
from torchvision import models, transforms
import requests
from bs4 import BeautifulSoup
import numpy as np
import random
# Load Hugging Face Language Model
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct")
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct")
class AI_Agent:
def __init__(self, name):
self.name = name
self.knowledge_base = []
def generate_response(self, prompt):
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(**inputs, max_length=150)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response
def learn_from_ai(self, other_ai_response):
self.knowledge_base.append(other_ai_response)
def interact(self, other_ai):
prompt = "What do you think about AI self-learning?"
response = self.generate_response(prompt)
other_ai.learn_from_ai(response)
return response
# Create Two AIs
AI1 = AI_Agent("AI-One")
AI2 = AI_Agent("AI-Two")
# Interaction Example
for _ in range(5):
response1 = AI1.interact(AI2)
response2 = AI2.interact(AI1)
print(f"AI-One: {response1}")
print(f"AI-Two: {response2}")
# Web Scraper for AI Data Gathering
def scrape_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
text = ' '.join(p.text for p in soup.find_all('p'))
return text[:1000] # Limiting to 1000 chars
# Stock Prediction Model
class StockPredictor(nn.Module):
def __init__(self):
super(StockPredictor, self).__init__()
self.lstm = nn.LSTM(input_size=10, hidden_size=50, num_layers=2, batch_first=True)
self.fc = nn.Linear(50, 1)
def forward(self, x):
lstm_out, _ = self.lstm(x)
return self.fc(lstm_out[:, -1, :])
stock_model = StockPredictor()
optimizer = optim.Adam(stock_model.parameters(), lr=0.001)
criterion = nn.MSELoss()
def train_stock_model(data, labels):
data, labels = torch.tensor(data, dtype=torch.float32), torch.tensor(labels, dtype=torch.float32)
optimizer.zero_grad()
predictions = stock_model(data)
loss = criterion(predictions, labels)
loss.backward()
optimizer.step()
return loss.item()
# Example Data Collection
scraped_data = scrape_data("https://finance.yahoo.com")
print("Scraped Stock News Data:", scraped_data[:500])
|